Академический Документы
Профессиональный Документы
Культура Документы
1.Array declaration
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.
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.
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:
2
Putting elements in an array:
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:
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:
Example 3:
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.
Usually in dealing with one dimensional array, you need to use one loop representing
array size as follows:
Each time the code is executed the user is free to fill the array with any names he
wants.
Example 4:
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):
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:
(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:
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
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:
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.
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).
7
3. Accessing the components of an array
1. OUDilaog.alert(roster[2]);
will prompt “John” in alert dialog box
3. roster[5].equals(roster[6]);
Will return false since roster[5] does not have the same state as roster[6]
6. OUDilaog.alert(roster[roster.length-2]);
Alert dialog box will show: “Agi”
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);
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:
1. Print the elements of array herbs which is declared and created as:
Solution:
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.
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.
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.
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.
//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:
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");
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:
position = i;
//shifting elements
for (int j = effectiveLength; j >= position; j--)
numArray[j+1]= numArray[j];
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:
if (anArray.length == anotherArray.length)
{
while ((i < anArray.length) && (identical))
{
if (anArray [i]!= anotherArray [i])
identical = false;
i++;
}
}
else
identical = false;
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
Example 5:
16
4.3 Printing two dimensional array (row-wise):
System.out.println();
}
Output:
1 3 5
7 9 11
System.out.println();
}
Output:
1 7
3 9
5 11
Exercise (6)
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;
Q4. Write a code to find the summation of each row and print it.
int sum;
Q5. Write a code to find the summation of each column and print it.
int 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);
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.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, 4, 8): this means sort part of array x from index 4 till
index 8, just sort these elements.
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 }};
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:
This code will create 10,001 different string objects and all but one of these is
unreferenced.
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:
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:
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.
== 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.
(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.trim(): return another copy of x where leading and trailing white spaces are
removed.
23
Exercise (8)
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"
18 bString.substring(6); "ndy"
24
7. StringBuilder class:
Example 9:
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
(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:
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.
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.
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.
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:
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.*;
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: ");
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;
} // end of class
After compiling this program you could run it as you learnt before.
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 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.
29
Class Work:
Q1.
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.
Solution:
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:
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:
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:
Q8.
Write a Java method that takes an array of String, and print the array in reverse order.
Solution:
System.out.println();
}
32