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

CMP-MX21: Lecture 3 Arrays and Strings Steve Hordley

Embed Size (px)

Citation preview

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();

TYPEVARIABLE

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

anArrayOfInts0 0 0 0

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

a24 16 47 14

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

a24 16 47 14

MEMORY

array values

33

MEMORY

ba 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

a24 16 47 21

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

MEMORY

b

3

After initialisation:

Simple variables

MEMORY

a

4

MEMORY

b

4

After: b = a;

After: b = 7;

MEMORY

a

4

MEMORY

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

24 16 47 21

MEMORY

array values

33

MEMORY

b

24 16 47 21

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 chars. 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: