You are on page 1of 32

M255

Object Oriented Programming with Java


Week 9 Prepared by: Dr. Bayan Abu Shawar,
AOU-Jordan
This lecture note covers unit 9.

This unit aims to cover:


• One and two dimensional arrays;
• Declaring Array of primitive data types and array of objects;
• Processing Arrays: reading, writing, searching, insertion, and deletion;
• String class and array of string;
• Built-in methods of String library;
• StringBuilder class and how it differs from String class;
• Writing a class using Notepad then compile and run it using window prompt.

1.Array declaration

An array is an object. It’s a sequence of memory locations (components) which:


• has fixed size,
• hold elements of the same data type (homogeneous).
• elements values could be primitive values as integer, double, or references to
objects.
• is an indexable structure, every item in an array is accessed by an integer index.

Simply an array is an indexable, fixed size collection whose elements are all of the
same type.

The general syntax to declare and create one dimensional array in Java is:

Declaring an array:
Data_Type[] array_name;

Creating an array:
array_name = new datat_Type[array_size];

Example 1:
double[] weights;

• Datat_Type: represents the data type the components of array will have which
could be primitive data types or references to objects.
• Square brackets [ ]: denote that this is an array
• array name: weights

Till now you just declare an array, but it is an object so you need to create this object.

weights = new double[6];

1
In this case the following array will be created as below:

Since the dated type is double, all components elements will initially hold 0.0 upon
creation.

Note that:
• The index is used to locate or access each component of the array. In Java array
index starts from 0, so the first component is at 0 index.
• If component type is :
o Numeric values it will be initialized to 0, 0.0
o String, char: it will be initialized to null
o boolean: it will be initialized to false
• Array size (length): should be an integer or any expression or variable that
evaluate to integer.

• To know length of array: array_name.length, not


array_name.lebgth().

Exercise (1):

1. Declare and create an array of type string called roster and with size 3 in a
single statement.
2. Declare and create an array x of type integer and size 2000 in a single
statement
3. Declare an create an array of type Frog with size 3 in a single statement call it
frogpond.

Solution:

1. String[] roster = new String[3];


2. int[] x = new int[2000];
3. Frog[] frogpond = new Frog[3];

2
Putting elements in an array:

You could initiliase (putting elements in) an array by 3 ways:


1. directly upon creation,
2. using assignment statements
3. at run time with reading process.

1. Initialisation upon creation

String[] roster = {“Jay”, “Bob”, “John”}

In this statement, an array roster is declared, and the expression on the right creates an
array of length 3 and assign its components to these values.

Example 2:

Frog[] frogpond = { new Frog(), new Frog(), new Frog()};

Initially frogpond will have three components, where each one poinst to a Frog
object where initial state of each frog is that: coulour is green, and position is one;

3
2. Putting elements using assignment statements:

To access any component of an array, or to put an element in an array: you need to


use:
Array_name[index] = element;

So another way to fill the array roster in previous example:

String roster = new String[3];


roster[0] = “Jay”;
roster[1] = “Bob”;
roster[2] = “John”;

Example 3:

Frog[] frogpond = new Frog[3]; //array of 3 objects

frogpond[0] = new Frog();

Frog temp = new Frog(); // one instance


temp.setPosition(2);
temp.setColour(OUColour.RED);

frogpond[1] = temp ;

You filled two elements of the array, the third component (frogpond[2]) still
points to null, so array frogpond will look like:

Note that:

Not all components contain real data, the third one still points to null. The effective
length of an array is the number of meaningful elements that has a real data.
In previous example, the effective length of roster array is 2.

In some cases you create an array of a big size, then you fill part of that array, and the
rest of elements have their initial values. In this case when you need to process the
array, you need to use the effective length not the whole length of the array.
4
Now this strategy of filling an array is inefficient if array size is 20, 100, or more. So
you could fill the array through reading process.

3. Putting elements into array through reading process:

Usually in dealing with one dimensional array, you need to use one loop representing
array size as follows:

for(int i=0; i< roster.length; i++)


roster[i] = OUDialog.request(“enter a name”);

Each time the code is executed the user is free to fill the array with any names he
wants.

Example 4:

As you know the property of substitutability allows to assign an object to a variable


declared to be of the type of one of its super-classes. For example:

Frog kermit = new HoverFrog();

is a valid statement, the same is applied for arrays.

Frog[] frogpond = new Frog[3];


frogpond[2] = new HoverFrog();

You could invoke any method from HoverFrog class:


frogpond[2].home();

Note that:
• Use each component of an array as any other variable to invoke any method in the
class.
• In terms of Frog object at index 2, if any method in Frog class is overridden in
HoverFrog, then the HoverFrog method will be executed. It will be easier if you
draw the reference diagram.

Exercise (2):

Is the following a valid declaration and initialisation of an array?


Object[] anArray = {new HoverFrog( ), new HoverFrog( ) };

Solution:

Yes, anArray has been declared with component type Object, which is a superclass of
HoverFrog.

Do Activity 2 Unit9-Page 23

5
Exercise (3)

Q1.
Assume you have the following array:

double weights = {60.1, 59.2, 58.3, 57.5, 58.5, 59.6, 58.4};

(a) What is the index of the component holding the element 57.5?
(b) What element is held by the component at index 5?

Solution:

(a) The index of the component holding the element 57.5 is 3.


(b) 59.6 is at index 5.

Q2.

(a) A business wants to store its revenue for a year, broken down in weekly sales
figures.Is an array a suitable collection structure for this task?

(b) A school wants to store records for each of its pupils. Is an array structure a
suitable collection in which to store the records?

Solution:

(a) Yes. There are a fixed number of weeks in a year, and this will not change.

(b) No. It is likely that pupils will leave the school, or join the school, and so the
number of student records is not fixed.

Q3.
(a) Write a declaration for an array variable, quizAnswer, which will reference an
array of boolean values.
(b) Write a declaration for an array variable, bank, which will reference an array of
references to Account objects.
Solution:
(a) boolean[] quizAnswer;
(b) Account[] bank;

Q4.
In your own words explain the terms: component, component type and element.

Solution

Component – An array consists of a fixed number of components. Each component is


like a variable and can hold a primitive value or reference to an object. However,
unlike variables which are identified by names, a particular component is identified by
providing the name of the variable that references the whole array, followed by the
index of the component in square brackets, for example myArray[s].
Component type – The type of the data that can be held by an array’s components.
Element – The value (either primitive value or object reference) that is held by a
component.

6
Q5. Create a new array of string objects called nameArray with size 6.
String[] nameArray = new String[6];

You should see the following window when you inspect nameArray:

Q6. Write a statement that will return the length of nameArray.


int size = nameArray.length;

Q7. Create a new array of string objects called nameArray with the following
names: "Ann", "Rob", "Kin", "Sue", "Fethi", "Jo"
String[] nameArray = {"Ann", "Rob", "Kin", "Sue", "Fethi", Jo"};;

Q8. Replace the string element "Sue", that is stored in nameArray, with "Lin".
nameArray[3]= "Lin";

Q9. Replace the name at index 2 of nameArray with a name entered by the user
using a dialogue box.

nameArray [2] = OUDialog.request("Please enter your name", "anonymous");

Q10. Create an array referenced by intArray that contains the integers 10, 5, 7,
2, 9, 8, 1 and 12 (in this order).
int[] intArray = {10, 5, 7, 2, 9, 8, 1, 12 };

Q11. Create an array, frogPond that can hold references to three Frog objects, and
assign a new Frog object to each component (the Frog objects should be in their initial
state).

Frog[] frogPond = new Frog [3];


frogPond [0]= new Frog( );
frogPond [1]= new Frog( );
frogPond [2]= new Frog( );

7
3. Accessing the components of an array

You need to use array_name[index] to access any element in the array.

Example: Assume you have the following array:

String[] roster = {“Jay”, “Bob”, “John”, “Anne”, “Ali”, “Agi”, “Jill”};

Then the following statements are valid:

1. OUDilaog.alert(roster[2]);
will prompt “John” in alert dialog box

2. String x = roster[0] + “ “ + roster[6];


x will have: “Jay Jill”

3. roster[5].equals(roster[6]);
Will return false since roster[5] does not have the same state as roster[6]

4. System.out.println(roster[2]); //print “John”

5. String name = roster[6].toUpperCase();


name will have: “JILL”

6. OUDilaog.alert(roster[roster.length-2]);
Alert dialog box will show: “Agi”

Assume you have the following array: int[] x = {7, 9, 3};

1. int y = x[1] + x[2]; // y = 9 + 3 = 12

2. int n = (x[1] – x[0]) / 2; // n = (9-7)/2 = 2 (integer division)

3. x[0] = x[0] + 1 ; // x[0] is assigned to 8

3.1 Accessing Objects in arrays:

The general format to accessing an array of object:


array_name[index].method_name();

Consider the array frogpond which contains references to three Frog objects as below:

8
1. To change the colour of the Frog object at index 1 to Red, and its position to 2:

frogpond[1].setColour(OUColour.RED);
frogpond[1].setPosition(2);

The array looks like:

2. To get the colour of the Frog object referenced by element at index 2:


frogpond[2].getColour();

3. To display the position of the Frog object referenced by the element at index 0 in a
dialog box is:

OUDialog.alert(String.ValueOf(frogpond[0].getPosition()));

4. To changes the colour of the Frog object referenced by the element at index 1 to
be the same as the colour of the Frog object referenced by the element at index 2.

frogpond[1].sameColourAs(frogpond[2]);

5. To evaluates true if the two Frog objects referenced by the elements at index 1 and
index 2 have the same position, and false otherwise.

frogpond[1].getPosition() == frogpond[2].getPosition();

2. Array Processing:

• Reading an array;
• Writing elements of an array;
• Finding Summation/average of array elements.
• Searching for an element in an array;
• Finding minimum or maximum in an array;
• Insert an element;
• Delete an element;

In all previous processing you need to use one loop to navigate the array.

9
2.1 Reading an array: to read elements of an array:

int[] y = new int[10];


String x;
for(int i=0; i< y.length; i++)
{
x = JOptionPane.showInputDialog("Enter an integer number");
y[i] = Integer.parseInt(x);
}

2.2 Filling array with elements:

1. Initialise an integer array x with 10, the size of x is 1000.

int[] x = new int[1000]; // array is filled with 0


for (int i=0; i< x.length; i++)
x[i] = 10;

2. Fill an array with elements, where each cell is incremented by 1 from


previous one.

int[] x = new int[1000];


for (int i=0; i< x.length; i++)
x[i] = x[i] + 1;

3. Declare and create an array of 10 frogs that refers to 10 objects.

Frog[] frogarray = new Frog[10];


for (int i=0; i< frogarray.length; i++)
frogarray[i] = new Frog();

4. An array called bank contains references to Account objects. Write a code to


increase balance of each object of array by 50$.

for (int i=0; i < bank.length; i++)


bank[i].credit(50);

2.3 Printing an array

1. Print the elements of array herbs which is declared and created as:

String[] herbs = {"basil", "rosemary", "thyme"};

Solution:

for (int i=0; i< herbs.length; i++)


System.out.println(herbs[i] + " ");

10
A novice programmer tries to print every element of an array using the following
for loop. What is wrong with his code?
for (int i = 1; i <= myArray.length; i++)
System.out.println(myArray [i ]);
Solution:
The code has two problems.
1. The loop variable i is initialised to 1 instead of 0, and so the element at index 0
will not be printed.
2. The Boolean condition controlling the loop (i <= myArray.length) will allow the
loop body to be executed when i is 2000. But myArray does not have an index
2000 so this will cause an ArrayIndexOutOfBounds exception.

2.4 Finding total/average of an array

1. Write a code to find the total (summation) of an integer array named


intArray.
int sum = 0;
for (int i=0; i< intArray.length; i++)
sum = sum + intArray[i];

System.out.println("Summation = " + sum);

2. Write a code to find the average of a banckAccount array which holds


elements refers to Account class. Find the average of customer balances.
double average, sum = 0;
for (int i = 0; i < banckAccount.length; i++)
sum = sum + banckAccount[i].getBalance();

average = (sum / banckAccount.length);


OUDialog.alert("Average balance is " + average);

2.5 Sequential Search for an element in an array

To search for an element, you assume that an element is not found, by declaring a
boolean variable and assign it to false. Then use while loop to check if an element is
found or not.

1. Write a method that returns true if an element x is found in an integer array


anArray, and returns false otherwise.

public Boolean seqsearch(int[] anArray)


{ int i = 0;
boolean found = false;

while ((i < anArray.length) && (! found))


{
if (anArray[i] == x)
found = true;
else
i++;
}
return found;
}

11
Note that: when you send an array as parameter, the argument in the method header
should denote that this is an array by using (data_Type[] array_name) without
mentioning size.

2. Suppose that searchValue is found in the array. Does the programmer know
where in the array it was found once the loop has exited?

Solution:

Yes! The variable i will hold the last index processed (the one where the value was
found). Note, though, that this code will find only the first occurrence of the value in
the array, there may be others.

2.6 Finding maximum/minimum of an array

To find the maximum or minimum, you need to assume that the first element of array
is min/max. Then use for loop to compare each element with max/min, and rewrite the
max/min value.

1. Write a code to do the following:


2. declare and create an integer array of 6 elements,
3. read array
4. find maximum of this array.

int[] x = new int[6];


//reading
String s;
for(int i = 0; i < x.length; i++)
{
s = JOptionPane.showInputDialog("Enter a grade");
x[i] = Integer.parseInt(s);
}

//maximum
int max = x[0]; //maximum = first element of array
for(int i=1; i < x.length; i++)
{ if ( x[i] > max)
max = x[i];
}
System.out.println("maximum is " + max);

12
Exercise (4)

Q1. Write a code to create a second array, intArrayCopy that is an exact copy of
intArray.

Solution:

int []intArrayCopy = new int [intArray.length ];

for (int i = 0; i < intArray.length; i++)


intArrayCopy [i ] = intArray [i ];

Q2. Write a code to:

Prompt the user to enter the desired length of an array (with a default option of 10),
and then create an int array called myArray of this length. The user should then be
repeatedly invited to enter a value (with a default option of 0) to be stored in the array.
The user should be prompted to enter exactly enough values to fill the components of
the array.

Solution:

String desiredLength;
String input;

desiredLength =
OUDialog.request("How many integers do you wish to store?", "10");

int []myArray = new int [Integer.parseInt(desiredLength) ];

for (int i = 0; i < myArray.length; i++)


{
input = OUDialog.request("Please enter an integer", "0");
myArray [i ]= Integer.parseInt(input);
}

2.6 Inserting an element into a sorted array

Assume you have an array in which not all it components are used. If this array is
sorted in ascending order, and you want to add an element x in its right position to
keep sorting, then you need to:
1. Search for right position by comparing each element with x using a for loop till
effective length.
2. Then shift elements from required position till effective length to left using for
loop
3. Then insert element in its right position

13
1. Write a Java code to insert an element x with value 10 in the following
integer array:

One of the Solutions is:

// assume you know effective length which is = 4

int position, x = 10, i = 0 ;


boolean found = false;
int effectiveLength = 4;

//finding right position


while ((i < numArray.length))
if (numArray[i] < x)
i++;

position = i;

//shifting elements
for (int j = effectiveLength; j >= position; j--)
numArray[j+1]= numArray[j];

numArray[position] = x; //adding element

Note that:

A solution will be easier if you are given the Effective Length of the array. But the
previous solution is general and could be applied to any array.

14
Exercise (5)

Q1.

Write a code to check if two int arrays, anArray and anotherArray, are identical arrays
(that is they contain exactly the same elements in the same order). Your code should
use a variable named identical that should hold either true if they are identical or false
otherwise.
Solution:

boolean identical = true;


int i = 0;

if (anArray.length == anotherArray.length)
{
while ((i < anArray.length) && (identical))
{
if (anArray [i]!= anotherArray [i])
identical = false;

i++;
}
}
else
identical = false;

Q2. Consider the following array:

Frog[] frogpond = { new Frog(), new Frog(), new Frog()};

Find the first occurrence of a red frog in this array. Display a dialog box that either
gives the index at which the first red frog is found, or announces that no red frogs
exist. Your code should work if:
• Array contains no red frogs,
• Exactly one red frog,
• More than one red frog.
Solution:

int i = 0;
boolean found = false;
while ((!found) && (i < frogPond.length))
{
if (frogPond [i ].getColour( ).equals(OUColour.RED))
found = true;

i++;
}

if (found)
OUDialog.alert("Red frog found at index " + (i-1));
else
OUDialog.alert("No red frogs found in this pond");

15
4. Two Dimensional Array

Two dimensional array looks like a table. It has rows and columns. In dealing with
two dimensional array, you need two nested loops to represent rows and coloumns.
You can process 2-D array eiter:
• row wise where outer loop represents row number, and inner represents column
number.
• coloumn wise where outer loop represents the column number and the inner for
row number

Creating and declaring two dimensional array:

Data_type[][] array_name = new datat_type[no_rows][no_coloums];

Example 5:

int[][] table = new int[3][4];

So the array looks like:

4.1 Initialising 2-D array:

int[][] table = { {1, 3, 5}, {7, 9, 11}};

4.2 Reading two dimensional array (row wise):

int[][] x = new int[3][4];


for (int i=0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
x[i][j] = Integer.parseInt(OUDialog.request("Enter a number"));
}

16
4.3 Printing two dimensional array (row-wise):

int[][] table = { {1, 3, 5}, {7, 9, 11}};


for (int i=0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
System.out.print(x[i][j]+ " ");

System.out.println();
}

Output:
1 3 5
7 9 11

4.4 Printing two dimensional array (column-wise):

int[][] table = { {1, 3, 5}, {7, 9, 11}};

for (int j=0; j < 4; j++) //no. of columns


{
for (int i = 0; i < 3; i++) //no. of rows
System.out.print(x[i][j]+ " ");

System.out.println();
}

Output:
1 7
3 9
5 11

Exercise (6)

Consider the following array:

int[][] y = new int[3][5];

Q1. Fill the last row with element 6.

for (int i=0; i< 5; i++)


y[2][i] = 6;

Q2. Fill column 4 with element 8.

for (int i=0; i< 3; i++)


y[i][4] = 8;

Note that: In sending 2-D array as parameter, in method header parameter you write
(datat_Type[][] array_name).

17
Q3. Write a method average that takes an integer two dimensional array
intTable that has 4 rows and 5 coloums, and displays its average.
public void average(int[][] intTable)
{
int sum = 0;

for (int i = 0; i < 4; i++)


{
for (int j = 0; j < 5; j++)
{
sum = sum + intTable [i][j];
}
}

double average = sum / 20.0;

OUDialog.alert("The average of all elements is " + average);


}

Q4. Write a code to find the summation of each row and print it.

int sum;

for (int i = 0; i < 4; i++)


{
sum = 0;
for (int j = 0; j < 5; j++)
{
sum = sum + intTable [i][j];
}
OUDialog.alert("Sum of row " + i + " is "+ sum);
}

Q5. Write a code to find the summation of each column and print it.

int sum;

for (int j = 0; j < 5; i++)


{
sum = 0;
for (int i = 0; i < 4; j++)
{
sum = sum + intTable [i][j];
}
OUDialog.alert("Sum of column " + j + " is "+ sum);
}

Q5. Write a code to find the summation of the diagonal from left to right and
print it.
int sum = 0;
for (int k=0; k < 4; k++)
sum = sum + intTable[k][k];
OUDialog.alert("Sum of diagonal is " + sum);

18
Q6. Write a code to find the summation of the diagonal from right to left and
print it.
int sum = 0;
for (int k=0; k < 4; k++)
sum = sum + intTable[k][3-k];
OUDialog.alert("Sum of diagonal is " + sum);

Note that: There is a multi-dimensional array, in which there are 3 or 4 dimensions


but it is beyond the scope of this module.

5. java.util.Arrays library

There is a Java library that provides built-in methods that saves you a lot of efforts
and programming. The Java library is: java.util.Arrays, some of its useful
class methods are:

• Arrays.toString(x): takes array x as argument, and returns it as a string


where contents of the array ‘topped’ and ‘tailed’ with square brackets. “[…….]”

• Arrays.deepToString(x): takes an array x as argument, and returns a


string representing array contents. If x is a two dimensional array, then each row
will be denoted in square brackets. i.e.
“[ [row1 elements], [row2 elements],….]”

• Arrays.equal(x,y): taking two arrays as arguments, then return true if two


arrays are equal (having same elements in same order), and return false otherwise.
If arrays elements are primitive data type, then == will be used, if elements are
objects then equals() method will be used.

• Arrays.deepEquals(x, y): returns true if two arrays are deeply equal, and
false otherwise. This is used in case of two or more dimensional array, it will
check row by row if they are identical.

• Arrays.sort(x): sorting array x in ascending order and store it in x itself.

• Arrays.sort(x, 4, 8): this means sort part of array x from index 4 till
index 8, just sort these elements.

• Arrays.fill(narray, z): taking an array narray and an initial value z,


then it will fill array with z vale in all its components as along as z matches
component type.

• Arrays.fill(narray, index1, index2, z): is to fill array narray


from index1 to index2 with value z as along as z matches component type.

• Arrays.binarySearch(narray, k): this will search array narray if k


elemnt is found or not using binary search technique. It will return index if
element is found, otherwise it will return a negative value. However, you could
use binary search if array is sorted.

19
Exercise (7):
Consider the following arrays:
int []firstIntArray = {9, 3, 7, 2, 8, 4, 10, 1, 5, 6 };
int []secondIntArray = {9, 3, 7, 2, 8, 4, 10, 1, 5, 6 };
String []firstStringArray = {"Bob", "Anne", "Alan" , "Mani" };
String [] secondStringArray ={"Mani", "Alan", "Bob", "Anne" };
int [][]firstTable ={{1, 3, 2 }, {5, 9, 4 }, {3, 7, 10 }, {8, 1,6 }};
int [][]secondTable = {{1, 3, 2 }, {5, 9,4 }, {3, 7,10 }, {8, 1,6 }};
int [][]thirdTable = {{3, 1, 2} , {5, 9, 4}, {3, 7, 10} , {8, 1,6 }};

Class method OutPut


1 Arrays.toString(firstIntArray); " [9, 3, 7, 2, 8, 4, 10, 1, 5, 6 ]"

2 Arrays.toString(firstStringArray); " [Bob, Anne, Alan, Mani ]"

3 Arrays.deepToString(secondTable); " [[1, 3, 2 ] , [5, 9, 4 ] [3, 7, 10 ] , [8, 1, 6 ]]"

4 Arrays.equals(firstIntArray, secondIntArray); true


5 Arrays.equals(firstStringArray, secondStringArray); false
6 Arrays.deepEquals(firstTable, secondTable); true
7 Arrays.sort(firstIntArray); {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }

8 Arrays.sort(firstStringArray); {"Alan", "Anne", "Bob", "Mani" }.

9 Arrays.fill(firstIntArray, 0); {0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }

10 Arrays.fill(secondIntArray, 2, 8, 100); {9, 3, 100, 100, 100, 100, 100, 100, 5, 6 }

Do Activity 5, Unit 9-Page 46.

6. Strings

String is an object that involves a sequence of characters. String differs than array by:

• Strings are constants, once a string has been created, its state cannot be
changed.
• String object responds to messages but non of them change String state.

Example 6:
String name = “Brian”;
This is stored as a sequence of characters:

20
6.1 String objects are Immutable:
Now if you write:
name = “Ali”;

In this case name identifier will refer to another memory location that has “Ali” as a
sequence of characters.

However, the previous String “Brian” is still in memory till it is garbage collector
work. So every time you alter a string, in fact you create another one.

We said that String objects are immutable, so once a String object is created, it
could not be changed. It will remain in memory till the garbage collector work.

Example 7:

String str = "";


for (int i = 1; i <= 10000; i++)
{
str = str + "*";
}

This code will create 10,001 different string objects and all but one of these is
unreferenced.

6.2 Equality and Identity of Strings:

In fact, whenever an attempt is made to create a string literal with exactly the same
sequence of characters as an existing string literal, a second reference to the original
String object is created instead. This means that only one copy of particular string
literal needs to be kept in the system at any one time. For example:

String string1 = “Brian”;


String string2 = “Brian”;

In this case, String2 will not create another object it will point to same object as
string1, we say string1 and string2 have the same identity, which means both of
them refer to same object. So at the end “Brian” is a n object which is referenced by
two different variables. The reference diagram will be:

21
If the created object is computed, then a distinct object will be created.

Example 8:

String name1 = "Jo";


String name2 = "Lo";
String name3 = "JoLo";
String name4 = name1 + name2;
String name5 = "Jo" + "Lo";
String name6 = new String("JoLo");

After execution:
• name1, name2, and name3 refer to three distinct objects.
• name4: will have value at run time, because the object will be computed, so
name 4 will have a distinct value.
• name5: will have its value at compilation time, so it will refer to same object
as name3.
• name6: will refer to a new distinct object.

So name3 and name5 have the same identity, both are


created as the same literal.

By literal means: set of characters inside double quotes: “..”

In terms of objects equality:

== when using it with objects, it sees if the two operands reference the same
object.

x.equals(y): checks if two objects have the same current state. This checks if
x and y contain the same characters in the same order.

Notice that uppercase letter differ than lowercase letters.

Consider the following statements:

String name1 = "Lee";


String name2 = "Ann";
String name3 = "LeeAnn";
String name4 = name1 + name2;
String name5 = "Lee" + "Ann";

What is the result of evaluating?

(a) name3.equals(name4);
returns true since both has the same current state (Same values)
(b) name3 == name4;
returns false, both of them refer to distinct objects even if they have the same
values.
(c) name3 == name5;
returns true, since both refers to same object, right hand side of both
variables is the same literal and they have the same identity.

22
Some of instance based method of String class

There are several instance based methods that you can use when dealing with strings.

• x.charAt(index): this returns the character that is found at index of string x

• x.compareTo(y): comparing two stings x and y together, this returns an


integer value that tells you how far apart in the character sequence the first
unequal characters are. Integer value could be:
ƒ negative: if x characters come before y characters
ƒ positive: otherwise
ƒ 0: if two string are exactly equal.

• x.indexOf(‘character’): it return an integer representing the index of


first occurrence of character argument, if it is not found it will return -1.

• x.indexOf(“str”): it will return the index of first character of str if argument


str is found as a substring in x

• x.replace(‘char1’, ‘char2’): it returns a new stirng where all


occurrence of char1 in string x is replaced by char2.

• x.trim(): return another copy of x where leading and trailing white spaces are
removed.

• x.length(): returns an integer representing number of characters in string x.


note length() here is a method not as array.length which is a variable.

• x.substring(index): returns a new string that has substring of x starting


from index till the end.

• x.substring(index1, index2): returns a new string that has substring of


x starting from index 1till index2.

• x.append(str2): will change the state of x by adding str2 to end of x string.

• x.deleteCharAt(index): change the state of x by removing the character at


index.

• x.insert(index, ‘char1’): change the state of x by inserting char1 at


index.

• x.reverse(): change state of x by reversing its characters.

23
Exercise (8)

Create the following String literals:

String aString = "Brian Aldridge";


String bString = "Ed Grundy";
String cString = "brian aldridge";
String dString =" a string with leading and trailing spaces ";

What will be the output in the following?

Expression Output
1 aString.charAt(4); 'n'

2 bString.charAt(0); ‘E’
3 aString.compareTo(bString); -3
4 bString.compareTo(aString); 3
5 aString.compareTo(cString); -32

6 aString.compareToIgnoreCase(cString); 0
7 aString.indexOf('i'); 2
8 bString.indexOf('G'); 3
10 cString.indexOf('B'); -1
11 aString.indexOf("Ald"); 6
12 bString.indexOf("ward"); -1
13 aString.replace('r', 'w'); "Bwian Alwidge"

14 bString.replace('d', 'm'); "Em Grunmy"

15 dString.trim( ); "a string with leading


and trailing spaces"
16 aString.length( ); 14

17 aString.substring(4); "n Aldridge"

18 bString.substring(6); "ndy"

19 cString.substring(3, 5); "an"

24
7. StringBuilder class:

The underlying representation of a StringBuilder object is also a sequence of character


values; however, for a StringBuilder object there is some buffer space so that the
number and sequence of characters can be changed. If the buffer turns out not to be
large enough to accommodate any changes, a new, and longer sequence is
automatically created and the characters moved over into it.

A StringBuilder object can be changed – it is mutable

Creating StringBuilder Objects:

There are several constructore of StringBuilder object:

1. StringBuilder( ) initialises an ‘empty’ StringBuilder object with the


potential to store 16 characters.

2. StringBuilder(String) initialises an instance of StringBuilder that


contains the same characters as the string argument plus buffer space for 16
additional characters.

For example, the code:


StringBuilder sb = new StringBuilder("Hello");

declares a StringBuilder variable referenced by sb, and assigns to it a new


instance of StringBuilder with the character sequence 'H' 'e' 'l' 'l' 'o', but with space
for an additional 16 characters, the object referenced by sb to contain 21
characters in total.

3. StringBuilder myStringBuilder = new StringBuilder(200);

A third constructor for StringBuilder allows the programmer to specify the


capacity of the buffer, which is the number of characters a StringBuilder object
can potentially hold

Example 9:

StringBuilder sb = new StringBuilder(10000);

for (int i = 1; i <= 10000; i++)


sb.append("*");

Only a single StringBuilder object ever exists.

In general, if the String object will change a lot, its better to define it as StringBuilder
not as String.

25
Note that:

The capacity( ) method, which returns the capacity of a StringBuilder object; and

length( ) which returns the number of characters currently in a StringBuilder


object.

The concatenation process: + is done in Java based on StringBuilder class. For


example:

"a" + 5 + "b" + 10;

The Java compiler implements this as follows:

(new StringBuilder("a")).append(5).append("b").append(10).toString( );

The fact that all the processing for the concatenations takes place in a single
StringBuilder object, and only at the end is the result converted back into a String,
means that far fewer temporary String objects have to be created, and if there are
many concatenations (for example, within a loop) this internal use of StringBuilder
means a big saving in memory and processing time.

StringBuilder’s Protocol:

The StringBuilder protocol uses the same method as String class.

In general, you can define and create an object of sequence of characters either as:
String or StringBuilder. The difference is that String object is immutable and
StingBuilder mutable which means it could be changed.

Example: Consider the following string:

StringBuilder aSB = new StringBuilder("Bob");

Expression OutPut
1 aSB.length(); 3
2 aSB.capacity(); 19
3 aSB.append(“ is “); 'B' 'o' 'b' ' ' 'i' 's' ' '

4 aSB.append(50); 'B' 'o' 'b' ' ' 'i' 's' ' ' '5' '0'
5 aSB.length(); 9
6 aSB.capacity(); 19
7 aSB.deleteCharAt(0); 'o' 'b' ' ' 'i' 's' ' ' '5' '0'
8 aSB.insert(0, ‘R’); 'R' 'o' 'b' ' ' 'i' 's' ' ' '5' '0'
9 aSB.reverse(); '0' '5' ' ' 's' 'i' ' ' 'b' 'o' 'R'
10 aSB.toString(); "05 si boR"

26
8. The main method

As we studied in previous units, the main method is written inside the class. We use
main method to run Java statements instead of using OUWorkspace.

The main method header is:

public static void main(String[] args)


{
<Body of main>
}

public: the main method is providing a starting point for the execution, so it should
be public to be available to outside world.

static: the mani() is the first method to be invoked, and at this point no object
exist. It should be static to remain alive till end of execution.

void: usually main method returns nothing

String[] args: the main method takes an array of String objects, this is used in
case an additional information is needed in order to execute body of the main method,
as an other method.

As we know, it’s better to divide code to more than method, then arrange Java
statements in main body to call other methods from this class or other classes.

The general structure for arranging methods inside the class including main is as
follows:

public class class_name


{
public static void main(String[] args)
{
method1();
int x = method2();
//calling other methods
……..
}

public void method1()


{
<method1 body>
}

public int method2()


{
<method2 body>
}
…………………….
}

27
Example 10:

Write a class called Test_Array where the class has the following methods:
• Method reading an array of grades
• Maximum method to return the maximum grade
• Average method that displays the average of grades.
• Brint method to print values of grade array
• Main method which declare and create an array of 10 grades, then invoke read
method, brint maximum, find the average of the array, then print array of grades.
Solution:

import javax.swing.*;

public class Test_Array


{
public static void main(String[] args)
{
int[] grades = new int[10];

Test_Array x = new Test_Array();

x.aread(grades);
x.brint(grades);
System.out.println("maximum grade is " + x.max(grades));
x.average(grades);
}
//*************************************************
public void aread(int[] g)
{ String x;
for(int i = 0; i < g.length; i++)
{
x = JOptionPane.showInputDialog("Enter a grade");
g[i] = Integer.parseInt(x);
}
}
//************************************************
public void brint(int[] g)
{
System.out.println("Array elements are: ");

for(int i = 0; i < g.length; i++)


System.out.println(g[i] + " ");
}

28
//************************************************
public int max(int[] g)
{ int max1 = g[0];
for(int i = 1; i < g.length; i++)
{
if (g[i] > max1)
max1 = g[i];
}

return max1;
}

//**************************************************
public void average(int[] g)
{
double sum = 0;

for(int i = 0; i < g.length; i++)


sum = sum + g[i];

System.out.println("Average = " + (sum/g.length) );

} // end of class

After compiling this program you could run it as you learnt before.

There is another way to write, compile and run a Java program:

1. Copy the previous code into Notepad.


2. Save it as Test_Array.java on My document folder. You need to put extension
name as all files instead of .txt, then in file name write it .java.
3. Open the command prompt window (StartÆ Program fileÆ
AccessoriesÆCommand prompt)
4. Compile your program: c:\> MyDocuments\javac TestArray.java
5. Run the program: c:\> MyDocuments\java TestArray

Note that:

• This method is used without using any Java environment, the only thing you need
is to have Java Development Kit on your computer.

• You could not use OUDialog because it is found in OU.*, which is not a library in
JDK

• You should save file as class name.

• You can do the same code into classes, where one of the classes has all methods
except main. The second class has the main method only.

Do Activity 8 Unit 9 Page 53

29
Class Work:

Q1.

Draw the array frogpond after executing the following code.

Frog[] frogpond = new Frog[3];


Frogpond[0] = new Frog();
Frog temp = new Frog();
temp.setPosition(2);
temp.setColour(OUColour.RED);
frogpond[1] = temp ;
temp.right();
temp.brown();

Solution:

The state of the Frog object referenced by temp will change, which means that the
component at index 1 of the array will also reference this changed object:

Q2.

Given the following code:


double []doubleArray = {2.5, 3.5, 2.0, 2.0 };

Describe the effect of each of these expressions:

(a) (doubleArray [1 ]+ doubleArray [0 ]) / doubleArray [3 ];

(b) doubleArray [3 ]= doubleArray [0 ] + doubleArray [1 ]


+ doubleArray [2 ];
(c) (int) doubleArray [1 ] > (int) doubleArray [3 ];

Solution:

(a) (3.5 + 2.5) / 2 is evaluated and the result is 3.0.

30
(b) (2.5 + 3.5 + 2.0) is evaluated and the result is 8.0. This is assigned to the
component at index 3 of doubleArray.

(c) The value of doubleArray [1 ]is cast to an int, which gives the result 2. The value
of doubleArray [3 ]is cast to an int, which also gives the result 2. 2 > 2 is evaluated,
and the result is false.

Q3.

(a) Write a single statement that both declares a variable bankBalances, and assigns to
it an array object that can hold 52 numbers of type double.
(b) Write a single statement that both declares a variable frogPond, and assigns to it
an array object that can hold references to three Frog objects.

Solution:

(a) double [] bankBalances = new double [52 ];


(b) Frog []frogPond = new Frog [3 ];

Q4:

In a single statement, declare an array variable, hours, with a component type of int,
and assign to it an array that has each of its 5 components initialised to 40.

Solution:

int [] hours = {40, 40, 40, 40, 40 };

Q5:

Write three assignment statements to populate the remaining three components of the
array referenced by weights (as it is shown in Figure 9) with double values.

Solution:

weights [4 ]= 58.5;
weights [5 ]= 59.6;
weights [6 ]= 58.4;

Q6:

Write the code to generate a dialogue box to request the user to enter their name (the
initial answer should be “anonymous”), and assign the response to the first component
of an array called roster. Assume the array variable has already been declared.

Solution:
roster [0 ] = OUDialog.request("Please enter your name","anonymous");

31
Q7.

Find all elements in an integer array x that are greater than 8 and replace each of them
by 0.

Solution:

for (int i = 0; i < x.length; i++)


{
if (x[i] > 8)
x[i] = 0;
}

Q8.

Write a Java method that takes an array of String, and print the array in reverse order.

Solution:

public void reverse(String[] names)


{
for(int i= names.length – 1; i >=0; i--)
system.out..println(" " + names[i]);

System.out.println();
}

32

You might also like