CMP-MX21: Lecture 3 Arrays and Strings Steve Hordley.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

CS0007: Introduction to Computer Programming Console Output, Variables, Literals, and Introduction to Type.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Chapter 10.
Variables Pepper. Variable A variable –box –holds a certain type of value –value inside the box can change Example –A = 2B+1 –Slope = change in y / change.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
Arrays Liang, Chpt 5. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Arrays Horstmann, Chapter 8. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Primitive Data Types byte, short, int, long float, double char boolean Are all primitive data types. Primitive data types always start with a small letter.
Understanding Arrays and Pointers Object-Oriented Programming Using C++ Second Edition 3.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 1 CMT1000: Introduction to Programming Ed Currie Lecture 5a: Input and.
Data types and variables
Introduction to Python
© The McGraw-Hill Companies, 2006 Chapter 6 Classes and objects.
Chapter 2 Data Types, Declarations, and Displays
Chapter 1 Program Design
Introduction to C Programming
Hello, world! Dissect HelloWorld.java Compile it Run it.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
CHAPTER 4: INTRODUCTION TO COMPUTER ORGANIZATION AND PROGRAMMING DESIGN Lec. Ghader Kurdi.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Fortran 1- Basics Chapters 1-2 in your Fortran book.
CMP-MX21: Lecture 6 Objects & Methods 1 Steve Hordley.
Introduction to Python
VARIABLES AND TYPES CITS1001. Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Scope.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
Unit 3: Java Data Types Math class and String class.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
Java Data Types. Primitive Data Types Java has 8 primitive data types: – char: used to store a single character eg. G – boolean: used to store true or.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
What does a computer program look like: a general overview.
Fundamental Programming: Fundamental Programming Introduction to C++
 Character set is a set of valid characters that a language can recognise.  A character represents any letter, digit or any other sign  Java uses the.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
CONSTANTS Constants are also known as literals in C. Constants are quantities whose values do not change during program execution. There are two types.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
Programming Fundamentals. Summary of previous lectures Programming Language Phases of C++ Environment Variables and Data Types.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Chapter 1: Introduction to Computers and Programming.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter 1.2 Introduction to C++ Programming
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Variables and Primative Types
Variables ,Data Types and Constants
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Java Programming Language
Primitive Types and Expressions
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Getting Started With Coding
Presentation transcript:

CMP-MX21: Lecture 3 Arrays and Strings Steve Hordley

Overview 2. An introduction to more complex variable types: arrays in JAVA 3. Simple variables versus reference variables 4. An introduction to JAVA Strings 1. Inputting data from the keyboard: re-using code

A problem Modify the simple calculator program from the previous lecture so that the user can enter data using the keyboard. The program should prompt the user to enter two integers, multiply them together and display the result.

Designing a solution What are the inputs/outputs of the program? Remember, when designing the solution to this problem we need to answer the following questions: What other data do we need in the program? How should we represent our data in the program? What operations will the program perform on the data?

Designing a solution Program inputs: two numbers and an operator Program output: a single number Data representation: input numbers and the result are floats. Tasks to be performed:1. Read two numbers from the keyboard 2. Multiply the two numbers 3. Write out the result

Reading from the keyboard For a variety of reasons, inputting and outputting data is not one of JAVA’s strengths: Interaction with the keyboard is done at quite a low-level in JAVA This means that a seemingly simple task such as reading a floating point number from the keyboard is quite difficult to program in JAVA Fortunately, because this task is so common, many people have written the code already. So, for the purposes of this course we will borrow someone else’s code

Re-usable code The ability to borrow or re-use existing code is a strength of JAVA Indeed, one of the driving forces behind object oriented programming in general is the wish to make it easy to re-use existing code When writing code we should aim to make it as general as possible so that parts of it can be re-used in other applications Proper program design is essential for achieving re-usable code

Re-using code In our programs we are going to use some existing code which makes it easy to read data from the keyboard This code contains methods (pieces of code) for performing tasks such as reading an integer or a double or a char, from the keyboard In our code we will simply call (use) whichever particular method we require to solve our problem

Re-using code The code we are going to borrow is contained in a file called keyboard.java The first step in using this code is to place the file in the directory with the rest of our code Next, we use the JAVA compiler to compile this code: C:>cd C:\myjavacode C:\myjavacode>javac keyboard.java This creates the compiled file keyboard.class

Re-using code Note: we cannot run this code as we would a normal program because it doesn’t contain a main method However, we can call methods from that file in our own program The first step in using methods from this class is to declare a new variable of type keyboard : Keyboard theKeyboard = new Keyboard(); TYPE VARIABLE NAME Code to reserve memory to hold the keyboard object

Re-using code Keyboard theKeyboard = new Keyboard(); This is similar to the variable declarations we have seen earlier but is not quite the same The details of what is happening here will become clear later in the course. For now we just accept that we need this line to be able to read from the keyboard The keyword new is a JAVA reserved word: we will look at its meaning later.

Reading from the keyboard int a; a = theKeyboard.readInt(); When this line is executed the program will wait for the user to enter a number and press the RETURN key. This number will then be stored in the integer variable a. We use similar code to read different types of data e.g. double or char data

Reading from the keyboard double a, b; char operator; a = theKeyboard.readDouble(); b = theKeyboard.readDouble(); operator = theKeyboard.readChar(); Here we are reading two doubles and a char. At each line the program waits for the user to enter data and press RETUR?N

Reading from the keyboard int a, b; System.out.println(“Enter the first number:”); a = theKeyboard.readInt(); System.out.println(“Enter the second number:”) b = theKeyboard.readInt(); We can improve the program by prompting the user to enter data:

Re-using code Now, we simply compile and run our program as usual: C:\>cd C:\myjavacode C:\myjavacode>javac readData.java C:\myjavacode>java readData Enter the first number: 16 Enter the second number: 12 16*12=192 C:\myjavacode>

A summary We have solved the problem of reading data from the keyboard by borrowing someone else’s code One way to think of this extra code is as an extension to the JAVA language: we are using the code as if it were built-in to JAVA It is important though that we are aware of what is and what is not part of the basic JAVA language The details of what is going on when we re-use code in this way we will become clearer in later lectures

Variables and types In the first lecture we looked at simple variables and saw that in JAVA there are 8 primitive types of variable: int, double, etc. These simple variables are useful for representing simple data: e.g. a person’s age might be represented with an int (or a byte ) their height could be represented by a float or a double their marital status by a char etc.

Variables and types In many cases though, it would be useful to be able to group certain data together For example, suppose we are interested in recording the age of 10 different people, it would be useful if we could somehow group this data together into a single entity Alternatively, suppose we need to record different data about a person: e.g. their age, height, and marital status. It would again be useful if such information could be grouped together

Variables and types JAVA allows us to do just these things - it is one of the most powerful features of JAVA and of object oriented programming in general In JAVA (and OO programming) a group of people’s ages or the collection of data for a person are called objects. All objects are formed by grouping simple variables together to form more complex variables In addition we can define certain functions which can be performed on these objects (more about this later)

The array type Certain complex variable types or objects are built in to JAVA because they are useful in a great many programs One such variable type is an array. An array is a list of values all of the same type For example, we can represent the ages of a group of people in an array We can think of an array as we think of other variables. As we come to understand JAVA better, we will see that arrays are more than just a type of variable

Declaring an array We declare an array in the following way: int[] anArrayOfInts; This declaration is very similar to our declaration of a simple variables The declaration means: “Declare a variable called anArrayOfInts which has a type of int[] Note that the square brackets denote that this an array (a list) of integers rather than a single integer

Some questions How many values (elements) are there in the list we have just declared? What is the default value of the variable anArrayOfInts To answer these questions we need to better understand what happens when we declare an array

Variable declarations When we declare a variable with one of JAVA’s eight primitive data types an area of memory is set aside and given a label (the variable name): MEMORY int anInt; anInt For example, when declaring an integer four bytes of memory are set aside and given a label

Array declarations When we declare a variable with to be of type int[] (array of ints) memory is again set aside and given a label: MEMORY int[] anArrayOfInts; anArrayOfInts But this memory does NOT contain the list of values itself but only a reference to where in memory the list of values is found

Reference variables MEMORY anArrayOfInts MEMORY array values An array variable is in fact an example of a reference variable. It contains a reference (or pointer) to an area of memory where some data is held (in this case, the list of values) We can think of a reference variable as containing an address to a certain area of memory. That is, it tells us where we can find the data we are interested in

Array declarations When we use a simple array declaration above all that happens is that an area of memory is set aside to hold the address of a set of values. It also defines what type of things we will find at this address: integers in this case. int[] anArrayOfInts; This array definition doesn’t define what the address is so JAVA gives it a default address of null. That is, by default our variable doesn’t point to anywhere

Initialising an array anArrayOfInts = new int[5]; Once we have declared an array we can initialise it in the following way: The keyword new sets aside an area of memory big enough to contain 5 integers. The address of this area of memory is assigned to the variable anArrayOfInts MEMORY anArrayOfInts 0000 MEMORY array values 0

Initialising an array int [] anArrayOfInts = new int[5]; Note, the integer values which form the array are given a default value of zero. Note, we could put the array declaration and its initialisation all on the same line: Effectively, new is declaring five integer variables Question: How can we access, and change the values of the array?

Setting array values Setting a single value (or element) of an array is done in the following way: anArrayOfInts[0] = 24; anArrayOfInts[1] = 16;... anArrayOfInts[4] = 33; int a; int[] b = new int[2]; b[1] = 4; a=b[1]; // Sets a=4; Accessing a single value (or element) of an array is done in the same way:

Accessing array values Attempting to access an array value outside this range will result in a compilation error: int [] anArrayOfInts = new int[5]; anArrayOfInts[5] = 1; // will not compile Note we can use a variable to access a given element of an array: int [] anArrayOfInts = new int[5]; int i=2; anArrayOfInts[i] = 1; // sets anArrayOfInts[2] to be 1 Array elements are numbered from 0 to the number of elements minus 1

Initialising an array int[] anArrayOfInts = {24, 16, 47, 14, 33}; Array initialisation can be performed with the single line: But this notation can only be used when the array is first declared. So, the following is not permissible: int[] anArrayOfInts = new int[5]; anArrayOfInts = {24, 16, 47, 14, 33}; // is not allowed

Some subtleties When using arrays we need to bear in mind that arrays are reference variables and not simple variables. That is, an array variable holds the address of some data rather than the data itself So, what does this section of code do?: int[] a = {24, 16, 47, 14, 33}; int[] b = new int[5]; b = a; b[3] = 21;

Array declarations MEMORY a MEMORY array values 33 MEMORY b null After the array declarations a contains the address to 5 integers which are initialised to 24, 16, 47, 14, and 33 The variable b contains a null address:

Array assignment b=a; The line Sets b equal to a. That is, it sets b equal to the same address as is held at a : MEMORY a MEMORY array values 33 MEMORY b a and b now point to the same memory

Array assignment b[3]=21; The line sets the fourth element which b points to, to 21: MEMORY a MEMORY array values 33 MEMORY b Note, changing b[3] has also changed a[3] (since a and b reference the same area of memory)

Simple variables int a = 4; int b = 3; b = a; b=7; Note, that a similar piece of code using simple variables does not have the same effect: MEMORY a 4 b 3 After initialisation:

Simple variables MEMORY a 4 b 4 After: b = a; After: b = 7; MEMORY a 4 b 7

Copying an array To properly copy an array we must use the following piece of code: int[] a = {24, 16, 47, 14, 33}; int[] b; b = (int[]) a.clone(); MEMORY a MEMORY array values 33 MEMORY b MEMORY array values 33

Copying an array b = (int[]) a.clone(); What is happening in the line that “copies” the array a ? clone is a method defined for arrays. A method is a function (a set of instructions) which acts on a. We will look more at methods in later lectures the method clone returns a value of type object which needs to be type cast to an integer array. (This will also become clearer in later lectures).

Some notes We are not restricted to arrays of ints : we can construct an array from any of the 8 primitive data types, e.g. boolean, double, char In fact, we can have arrays of any kind of data object we define including arrays of arrays! There are other methods defined for arrays, e.g. the length method can be used to determine the number of elements in an array: int[] myArray = {1,2,3}; int arrayLength; arrayLength = a.length(); // arrayLength = 3

Strings Often our programs will need to handle lists of letters (e.g. sentences) One way to handle this would be to use an array of type char But JAVA has a special data structure called the String Class to handle this type of data We will look at strings in the rest of this lecture

Strings In JAVA a string is a list of one or more character ( char ) elements. Just like for the char data type, any UNICODE character is a valid element of a string A string literal is any sequence of unicode characters surrounded by double quotation marks: “my first string” We can declare a variable to be of type String in a similar way to how we declare other types of variable: String myString;

Initialisation and assignment Variable initialisations are also made in a similar way: String myString; myString = “my first string”; String myString = “my first string”; Or: Note, the data type is String and not string (the capitalisation is important)

The String type Like an array variable, a String variable is a reference variable not a simple variable. That is, it contains an address to the location of some string data So far, the String type is no more than an array of char s. In fact, the String type is much more powerful than this The power of the String type comes from the many built-in methods which are defined for it and which allow us to perform many text analysis tasks

Some String methods The length of a string can be found using the length method: String myString = “my first string”; int len; len = myString.length; //len is 15 Any single character of a string can be accessed using the charAt method: String myString = “my first string”; char theChar; theChar = myString.charAt(3); //theChar is ‘f’ Note, like arrays, string numbering begins at 0

Some String methods A substring of a String can be accessed using the substring method: String myString = “my first string”; String anotherString; anotherString = myString.substring(3,7); // anotherString is “first” Other String methods exist to compare two strings, convert a string from upper to lower case, etc. A complete list of String methods can be found in the JAVA documentation

Combining String variables Two strings can be combined to produce a new string in the following way: String myString = “this string”; String anotherString=“that string; String thirdString; thirdString = myString+anotherString; // thirdString is “this stringthat string” When its arguments are of String type, JAVA understands the + operator to mean combine the two strings end to end

Strings and numbers Sometimes it is useful to be able to convert a number (e.g. an int ) to a String. For example, we might want to convert the number 1234 to the number “1234”. There is a method to do this: int num = 1234; String myString; myString = String.valueOf(num); The method can be used on different types also: boolean myBool = false; String myString; myString = String.valueOf(myBool); // myBool = “false”

Strings and numbers It is also useful to be able to convert from a String to e.g. an int. JAVA has a method to do this, although it is not a method of the String class: int num; String myString=“1234”; myString = Integer.parseInt(myString); parseInt is a method of the Integer class which is built in to JAVA. The Integer class contains methods to perform a variety of tasks with integers. (In fact, we saw this method in the previous lecture …)

Strings and numbers // A simple calculator class myMultiplier { public static void main( String [] args ) {... a = Integer.parseInt(args[0]); b = Integer.parseInt(args[1]);... }

Strings and command line arguments public static void main( String [] args ) The first line of our program should now make more sense: This piece of code declares an array of String called args. Each command line argument is held in an element of the array args. Each command line argument has a type of String.

Strings and command line arguments a = Integer.parseInt(args[0]); args[0] accesses the first element of the array parseInt converts its argument into an integer.

A summary In this lecture we have looked at two new variable types arrays and String These types are more powerful than the primitive types we looked at in the first lecture. They have associated with them methods: functions to perform certain tasks that often be performed with this type of data We have seen that arrays and Strings are reference variables and we have explored the difference between reference variables and simple variables

A summary You should now understand the following words and symbols in the JAVA language [], null, new, String length, clone, charAt, substring, valueOf In addition you should be familiar with the following methods which can be used with arrays or strings: