1/28
Prof. Moheb Ramzy Girgis
Department of Computer Science Faculty of Science
Minia University
Java Programming
7. Arrays
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Introduction
Often you will have to store a large number of values during the execution of a program.
Suppose we need to read 100 numbers, compute their average, and find out how many numbers are above the average.
We have to declare 100 variables and repeatedly write almost identical code 100 times. Writing a program this way would be impractical.
An efficient, organized approach is needed. Java and most other high-level languages provide the array data structure.
An Array stores a fixed-size sequential collection of elements of the same type.
Thus, instead of declaring individual variables, such as num0, num1, …, and num99, we declare one array variable such as nums and use nums[0], nums[1], …, and nums[99] to represent individual variables.
2/28
Declaring and Creating Array Variables
To use an array in a program, you must declare a variable to reference the array and specify the array’s element type.
Here is the syntax for declaring an array variable:
elementType[] arrayRefVar;
The elementType can be any data type, and all elements in the array will have the same data type.
For example, the following code declares a variable myList that references an array of double elements.
double[] myList
;
The declaration of an array variable does not allocate any space in memory for the array. It creates only a storage location for the reference to an array.
If a variable does not contain a reference to an array, the value of the variable is null.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
You cannot assign elements to an array unless it has already been created.
After an array variable is declared, you can create an array by using the newoperator with the following syntax:
arrayRefVar = new elementType[arraySize];
This statement does two things:
1) it creates an array using new elementType[array-Size];
2) it assigns the reference of the newly created array to the variable arrayRefVar.
Declaring and creating array variable can be combined in one statement, as shown below:
elementType[] arrayRefVar = new elementType[arraySize];
For example the statement: double[] myList = new double[10];
declares an array variable, myList, creates an array of ten elements of double type, and assigns its reference to myList.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Declaring and Creating Array Variables
3/28
You cannot assign elements to an array unless it has already been created.
To assign values to the elements, use the syntax:
arrayRefVar[index] = value;
For example, the following code initializes the array:
myList[0] = 5.6;
myList[1] = 4.5;
myList[2] = 3.3;
myList[3] = 13.2;
myList[4] = 4.0;
myList[5] = 34.33;
myList[6] = 34.0;
myList[7] = 45.45;
myList[8] = 99.993;
myList[9] = 11123;
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Declaring and Creating Array Variables
Array Size and Default Values
When space for an array is allocated, the array size must be given, specifying the number of elements that can be stored in it.
The size of an array cannot be changed after the array is created.
Size can be obtained using arrayRefVar.length.
For example, myList.length is 10.
When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types (0 for int, 0.0 for double), '\u0000' for char types, and false for boolean types
.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
4/28
Array Indexed Variables
The array elements are accessed through the index.
Array indices are 0 based; that is, they range from 0 to arrayRefVar.length-1.
In the example in Slide 5, myList holds ten double values, and the indices are from 0 to 9.
Each element in the array is represented using the following syntax, known as an indexed variable:
arrayRefVar[index];
For example, myList[9] represents the last element in the array myList.
After an array is created, an indexed variable can be used in the same way as a regular variable.
For example, the statement myList[2] = myList[0] + myList[1];
adds the values in myList[0] and myList[1] to myList[2].
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Array Initializers
Java has a shorthand notation, known as the array initializer, which combines in one statement declaring an array, creating an array, and initializing, using the following syntax:
elementType[] arrayRefVar = {value0, value1, ..., valuek};
For example,
double[] myList = {1.9, 2.9, 3.4, 3.5};
This statement declares, creates, and initializes the array myList with four elements, which is equivalent to the statements shown below:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
5/28 Caution
The new operator is not used in the array-initializer syntax.
Using an array initializer, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error.
Thus the next statement is wrong:
double[] myList;
myList = {1.9, 2.9, 3.4, 3.5};
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
Array Initializers
Processing Arrays
When processing array elements, you will often use a for loop—for two reasons:
All of the elements in an array are of the same type. They are evenly processed in the same fashion repeatedly using a loop.
Since the size of the array is known, it is natural to use a for loop.
Assume the array is created as follows:
double[] myList = new double[10];
Following are some examples of processing arrays:
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
6/28
Processing Arrays
1. Initializing arrays with input values:
The following loop initializes the array myList with user input values:
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++) myList[i] = input.nextDouble();
2. Initializing arrays with random values:
The following loop initializes the array myList with random values between 0.0 and 100.0, but less than 100.0:
for (int i = 0; i < myList.length; i++) { myList[i] = Math.random() * 100;
}
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
Processing Arrays
3. Displaying arrays:
To print an array, you have to print each element in the array using a loop like the following:
for (int i = 0; i < myList.length; i++) { System.out.print(myList[i] + " ");
}
For an array of the char[] type, it can be printed using one print statement. For example, the following code displays Dallas:
char[] city = {'D', 'a', 'l', 'l', 'a', 's'};
System.out.println(city);
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
7/28
Processing Arrays
4. Summing all elements:
Use a variable named totalto store the sum. Initially total is 0.
Add each element in the array to total using a loop like this:
double total = 0;
for (int i = 0; i < myList.length; i++) { total += myList[i];
}
5. Finding the largest element:
Use a variable named maxto store the largest element.
Initially max is myList[0]. To find the largest element in the array myList, compare each element with max, and update max if the element is greater than max.
double max = myList[0];
for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i];
}
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Processing Arrays
6. Finding the smallest index of the largest element:
Often you need to locate the largest element in an array. If an array has more than one largest element, find the smallest index of such an element.
Suppose the array myList is 1, 5, 3, 4, 5, 5. The largest element is 5 and the smallest index for 5 is 1.
Use a variable named maxto store the largest element and a variable named indexOfMaxto denote the index of the largest element. Then, use the following code:
double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < myList.length; i++) { if (myList[i] > max) {
max = myList[i];
indexOfMax = i;
}
} Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
What is the consequence if (myList[i] > max)
is replaced by (myList[i] >= max)?
8/28
Processing Arrays
7. Random shuffling:
Sometimes you need to randomly reorder the elements in an array. This is called a shuffling. To accomplish this, for each element myList[i], randomly generate an index j and swap myList[i] with myList[j], as follows:
for (int i = 0; i < myList.length; i++) { // Generate an index j randomly
int j= (int) (Math.random() * mylist.length);
// Swap myList[i] with myList[j]
double temp = myList[i];
myList[i] = myList[j]
myList[j] = temp;
}
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Processing Arrays
8. Shifting elements:
Sometimes you need to shift the elements left or right.
An example to shift the elements one position to the left and fill the last element with the first element:
double temp = myList[0]; // Retain the first element // Shift elements left
for (int i = 1; i < myList.length; i++) { myList[i - 1] = myList[i];
}
// Move the first element to fill in the last position myList[myList.length - 1] = temp;
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
9/28
For-each Loop
Java supports a convenient for loop, known as a for-each loop or
enhanced for loop, which enables you to traverse the array sequentially without using an index variable.
For example, the following code displays all the elements in the array myList:
for (double u: myList) { System.out.println(u);
}
You can read the code as “for each element u in myList do the following.”
Note that the variable, u, must be declared the same type as the elements in myList.
In general, the syntax for a for-each loop is for (elementType element: arrayRefVar) {
// Process the element }
You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array.
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
Processing Arrays: Example
Write a program that reads the test scores of 5 students, calculates their average, then determines and displays which scores are above, equal, and below the average
(Explained in the lecture)
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University 34
10/28
Copying Arrays
Often you need to duplicate an array or a part of an array. In such cases you could attempt to use the assignment statement (=), as follows:
list2 = list1;
This statement does not copy the contents of the array referenced by list1 to list2, but merely copies the reference value from list1 to list2.
After this statement, list1 and list2 reference to the same array, as shown in the figure. The array previously referenced by list2 is no longer referenced; it becomes garbage, which will be automatically collected by the Java Virtual Machine.
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
Copying Arrays
There are three ways to copy the contents one array to another:
Use a loop to copy individual elements one by one.
Use the static arraycopy method in the System class.
Use the clonemethod to copy arrays; this will be introduced later.
You can write a loop to copy every element from the source array to the corresponding element in the target array.
The following code, for instance, copies sourceArray to targetArray using a for loop.
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];
for (int i = 0; i < sourceArray.length; i++) { targetArray[i] = sourceArray[i];
}
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
11/28
Copying Arrays
Another approach is to use the arraycopy method in the java.lang.System class to copy arrays instead of using a loop.
The syntax for arraycopy is shown below:
arraycopy(sourceArray, src_pos, targetArray, tar_pos, length);
The parameters src_pos and tar_pos indicate the starting positions in sourceArray and targetArray, respectively. The number of elements copied from sourceArray to targetArray is indicated by length.
For example, you can rewrite the loop using the following statement:
System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
After the copying takes place, targetArray and sourceArray have the same content but independent memory locations.
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
Passing Arrays to Methods
public static void printArray(int[] array) { for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
} }
You can invoke it by passing an array. For example, the following code invokes the printArray method to display 3, 1, 2, 6, 4, and 2.
int[] list = {3, 1, 2, 6, 4, 2};
printArray(list);
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
Just as you can pass primitive type values to methods, you can also pass arrays to methods.
For example, the following method displays the elements in an int array:
12/28
Pass By Value
Java uses pass by value to pass arguments to a method.
There are important differences between passing a value of variables of primitive data types and passing arrays.
For a parameter of a primitive type value, the actual value is passed. Changing the value of the local parameter inside the method does not affect the value of the variable outside the method.
For a parameter of an array type, the value of the parameter contains a reference to an array; and this reference is passed to the method. Any changes to the array that occur inside the method body will affect the original array that was passed as the argument.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
This program demonstrate the differences between passing primitive data type variables and passing array variables.
public class Test {
public static void main(String[] args) { int x = 1; //x represents an int value
int[] y = new int[10]; //y represents an array of int values m(x, y); // Invoke m with arguments x and y
System.out.println("x is " + x);
System.out.println("y[0] is " + y[0]);
}
public static void m(int number, int[] numbers) {
number = 1001; //Assign a new value (1001) to number
numbers[0] = 5555; //Assign a new value (5555) to numbers[0]
} }
Pass By Value: Example 1
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Output
13/28
This program shows the difference between passing elements of an array and passing the whole array to methods.
public class TestPassArray {
public static void main(String[] args) { int[] a = {1, 2};
// Swap elements using the swap method System.out.println("Before invoking swap");
System.out.println("array is {" + a[0] + ", " + a[1] + "}");
swap(a[0], a[1]);
System.out.println("After invoking swap");
System.out.println("array is {" + a[0] + ", " + a[1] + "}");
// Swap elements using the swapFirstTwoInArray method System.out.println("Before invoking swapFirstTwoInArray");
System.out.println("array is {" + a[0] + ", " + a[1] + "}");
swapFirstTwoInArray(a);
System.out.println("After invoking swapFirstTwoInArray");
System.out.println("array is {" + a[0] + ", " + a[1] + "}");
}
Pass By Value: Example 2
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
/** Swap two variables */
public static void swap(int n1, int n2) { int temp = n1;
n1 = n2;
n2 = temp;
}
/** Swap the first two elements in the array */
public static void swapFirstTwoInArray(int[] array) { int temp = array[0];
array[0] = array[1];
array[1] = temp;
} }
Pass By Value: Example 2
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
Output
The two elements
are not swapped
The two elements are
swapped
14/28
Returning an Array from a Method
A method may return an array.
For example, the method shown below returns an array that is the reversal of another array:
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
public static int[] reverse(int[] list) { int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i];
}
return result;
}
Assume array list1is declared and initialized as follows:
int[] list1 = {1, 2, 3, 4, 5, 6};
The following statement returns a new array list2with elements 6, 5, 4, 3, 2, 1.
int[] list2 = reverse(list1);
Case Study: Counting the Occurrences of Each Letter
Write a program to count the occurrences of each letter in an array of characters.
The program does the following:
1. Generate 100 lowercase letters randomly and assign them to an array of characters.
2. Count the occurrences of each letter in the array. To do so, create an array, say counts, of 26 int values, each of which counts the occurrences of a letter. That is, counts[0] counts the number of a’s, counts[1] counts the number of b’s, and so on.
Firstly, write a method to get a random letter:
public static char getRandomLowerCaseLetter() { return (char)('a' + Math.random() * ('z' - 'a' + 1));
} Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science
Minia University
15/28
Case Study: Counting the Occurrences of Each Letter
Secondly, write a method to generate 100 lowercase letters randomly, assign them to an array of characters, and return the array
public static char[] createArray() {
// Declare an array of characters and create it char[] chars = new char[100];
// Create lowercase letters randomly and assign them to the array for (int i = 0; i < chars.length; i++)
chars[i] = getRandomLowerCaseLetter();
// Return the array return chars;
} // End of createArray
Thirdly, write a method to count the occurrences of each letter public static int[] countLetters(char[] chars) {
// Declare and create an array of 26 int int[] counts = new int[26];
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Case Study: Counting the Occurrences of Each Letter
// For each lowercase letter in the array, count it for (int i = 0; i < chars.length; i++)
counts[chars[i] - 'a']++;
return counts;
} // End of countLetters
Fourthly, write a method to display the array of characters public static void displayArray(char[] chars) {
// Display the characters in the array 20 on each line for (int i = 0; i < chars.length; i++) {
if ((i + 1) % 20 == 0)
System.out.println(chars[i]);
else
System.out.print(chars[i] + " ");
}
} // End of displayArray
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
16/28
Case Study: Counting the Occurrences of Each Letter
Fifthly, write a method to display the counts of the occurrences of each letter
public static void displayCounts(int[] counts) { for (int i = 0; i < counts.length; i++) {
if ((i + 1) % 10 == 0)
System.out.println(counts[i] + " " + (char)(i + 'a'));
else
System.out.print(counts[i] + " " + (char)(i + 'a') + " ");
}
System.out.println();
} // End of displayCounts
Finally, write the main method
public static void main(String[] args) { // Declare and create an array char[] chars = createArray();
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Case Study: Counting the Occurrences of Each Letter
// Display the array
System.out.println("The lowercase letters are:");
displayArray(chars);
// Count the occurrences of each letter int[] counts = countLetters(chars); // Display counts
System.out.println();
System.out.println("The occurrences of each letter are:");
displayCounts(counts);
} // End of main
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Sample run
17/28
Using Parallel Arrays
Parallel arrays: two or more arrays that contain related data
Subscript is used to relate arrays
elements at same subscript are related
The arrays do not have to hold data of the same type
Example:
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
final int SIZE = 5;
String [] name = new String [SIZE]; // student name double [] average = new double [SIZE]; // course average char [] grade = new char [SIZE]; // course grade
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
name average grade
50
Parallel Array Processing
public class parallelArray {
public static void main(String[] args) {
String [] name = {"Sam", "Fred", "Jim", "Tom", "David"};
// student name double [] average = {85, 64, 70, 45, 96}; // course average char [] grade = {'B', 'D', 'C', 'F', 'A'}; // course grade // Display the contents of the three parallel arrays System.out.println("Student\tAverage\tGrade");
for (int i = 0; i < name.length; i++)
System.out.println(name[i] + "\t" + average[i] + "\t" + grade[i]);
} }
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University 51
Sam Fred Jim Tom David 0
1 2 3 4
85 64 70 45 96 0 1 2 3 4
'B' 'D' 'C' 'F 'A 0 1 2 3 4
name average grade
Student Average Grade
Sam 85.0 B
Fred 64.0 D
Jim 70.0 C
Tom 45.0 F
David 96.0 A Output
18/28
Searching Arrays
Searching is the process of looking for a specific element in an array; for example, discovering whether a certain score is included in a list of scores.
Searching is a common task in computer programming.
There are many algorithms and data structures devoted to searching.
One of the common search algorithms is the linear search algorithm.
It compares the key element keysequentially with each element in the array. It continues to do so until the key matches an element in the array or the array is exhausted without a match being found.
If a match is made, the linear search returns the index of the element in the array that matches the key.
If no match is found, the search returns -1.
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
Searching Arrays
The linearSearch method:
/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) { for (int i = 0; i < list.length; i++) {
if (key == list[i]) return i;
}
return -1;
}
Examples:
int[] list = {1, 4, 4, 2, 5, -3, 6, 2};
int i = linearSearch(list, 4); // Returns 1 int j = linearSearch(list, -4); // Returns -1 int k = linearSearch(list, -3); // Returns 5
The linear search method compares the key with each element in the array. The elements can be in any order.
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
19/28
54
Trace of the linearSearch method
6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8
3
3
3
3
3
3
Key List
key == list[0] = false
[0] [1] [2] [3] [4] [5] [6] [7]
key == list[1] = false
key == list[2] = false
key == list[3] = false
key == list[4] = false
key == list[5] = true
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
The Arrays Class
The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all
primitive types.
The sort method sorts a whole array or a partial array.
For example, the following code sorts an array of numbers and an array of characters:
double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};
java.util.Arrays.sort(numbers); // Sort the whole array char[] chars = {'a', 'A', '4', 'F', 'D', 'P'};
java.util.Arrays.sort(chars, 1, 3); // Sort part of the array from // chars[1] to chars[3-1]
The binarySearch method searches for a key in an array.
The array must be presorted in increasing order. If the key is not in the array, the method returns –(insertion index + 1).
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
20/28
The Arrays Class
For example, the following code searches the keys in an array of integers:
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
System.out.println("(1) Index is " + java.util.Arrays.binarySearch(list, 11));
System.out.println("(2) Index is " +
java.util.Arrays.binarySearch(list, 12));
The equals method checks whether two arrays are equal.
Two arrays are equal if they have the same contents.
In the following code, list1 and list2 are equal, but list2 and list3 are not.
int[] list1 = {2, 4, 7, 10};
int[] list2 = {2, 4, 7, 10};
int[] list3 = {4, 2, 7, 10};
System.out.println(java.util.Arrays.equals(list1, list2)); // true System.out.println(java.util.Arrays.equals(list2, list3)); // false
Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
(1) Index is 4 (2) Index is -6
Output
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Multidimensional Arrays
You have learned how to use one-dimensional arrays to store linear collections of elements.
You can use a two-dimensional array to store a matrix or a table.
For example, the following table that describes the distances between the cities can be stored using a two-dimensional array.
21/28
Declaring and Creating Two-Dimensional Arrays
The syntax for declaring a two-dimensional array:
elementType[][] arrayRefVar;
For example, you can declare a two-dimensional array reference variable matrix of int values as follows:
int[][] matrix;
You can create a two-dimensional array of 5-by-5 int values and assign it to matrix as follows :
matrix = new int[5][5];
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Two subscripts are used in a two- dimensional array, one for the row and the other for the column.
As in a one-dimensional array, the index for each subscript is of the inttype and starts from 0, as shown in the figure.
Declaring and Creating Two-Dimensional Arrays
To assign the value 7 to a specific element at row 2 and column 1, as shown in the figure, you can use the statement:
matrix[2][1] = 7;
You can also use an array initializer to declare, create, and initialize a two- dimensional array.
For example, the following code in (a) creates an array with the specified initial values, as shown in the figure.
This is equivalent to the code in (b).
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
22/28
Obtaining the Lengths of Two-Dimensional Arrays
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
A two-dimensional array is a one-dimensional array in which each element is another one-dimensional array.
The length of an array x is the number of elements in the array, which can be obtained using x.length, where x[0], x[1], and x[x.length-1] are arrays. Their lengths can be obtained using x[0].length, x[1].length, and x[x.length-1].length.
For example, suppose x = new int[3][4],
x[0], x[1], and x[2] are one-dimensional arrays and each contains four elements. x.length is 3, and x[0].length, x[1].length, and x[2].length are 4, as shown in the figure.
Ragged Arrays
Each row in a two-dimensional array is itself an array. Thus the rows can have different lengths. An array of this kind is known as a ragged array.
An example of creating a ragged array:
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
As can be seen, triangleArray[0].length is 5,
triangleArray[1].length is 4, triangleArray[2].length is 3, triangleArray[3].length is 2, and triangleArray[4].length is 1.
23/28
Ragged Arrays
If you don’t know the values in a ragged array in advance, but know the sizes, say the same as before, you can create a ragged array using the syntax that follows:
int[][] triangleArray = new int[5][];
triangleArray[0] = new int[5];
triangleArray[1] = new int[4];
triangleArray[2] = new int[3];
triangleArray[3] = new int[2];
triangleArray[4] = new int[1];
You can now assign values to the array. For example, triangleArray[0][3] = 50;
triangleArray[4][0] = 45;
The syntax new int[5][] for creating an array requires the first index to be specified. The syntax new int[][] would be wrong.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Processing Two-Dimensional Arrays
Suppose an array matrix is created as follows:
int[][] matrix = new int[10][10];
Here are some examples of processing two-dimensional arrays:
1) Initializing arrays with input values: The following loop initializes the array with user input values:
java.util.Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and " + matrix[0].length + " columns: ");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) { matrix[row][column] = input.nextInt();
} }
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
24/28
Processing Two-Dimensional Arrays
2) Initializing arrays with random values: The following loop initializes the array with random values between 0 and 99:
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length ; column++) { matrix[row][column] = (int)(Math.random() * 100);
} }
3) Printing arrays: To print the elements of a two-dimensional array, you have to use a loop like the following:
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) { System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Processing Two-Dimensional Arrays
4) Summing all elements: Use a variable named total to store the sum. Initially total is 0. Add each element in the array to total using a loop like this:
int total = 0;
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length ; column++) { total += matrix[row][column];
} }
5) Summing elements by column : For each column, use a variable named total to store its sum. Add each element in the column to total using a loop like this:
for (int column = 0; column < matrix[0].length; column++) { int total = 0;
for (int row = 0; row < matrix.length; row++) { total += matrix[row][column];
}
System.out.println("Sum for column " + column + " is " + total);
} Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science
Minia University
25/28
Processing Two-Dimensional Arrays
6) Which row has the largest sum?: Use variables maxRow and indexOfMaxRow to track the largest sum and index of the row.
For each row, compute its sum and update maxRow and indexOfMaxRow if the new sum is greater.
int maxRow = 0;
int indexOfMaxRow = 0;
// Get sum of the first row in maxRow
for (int column = 0; column < matrix[0].length; column++) maxRow += matrix[0][column];
for (int row = 1; row < matrix.length; row++) { int totalOfThisRow = 0;
for (int column = 0; column < matrix[row].length; column++) totalOfThisRow += matrix[row][column];
if (totalOfThisRow > maxRow) { maxRow = totalOfThisRow;
indexOfMaxRow = row;
} }
System.out.println("Row " + indexOfMaxRow + " has the maximum sum of " + maxRow); Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science
Minia University
Problem: Grading a Multiple-Choice Test
The problem is to write a program that grades multiple-choice tests. Suppose there are eight students and ten questions, and the answers are stored in a two-dimensional array. Each row records a student’s answers to the questions, as shown in the following array.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
The key is stored in a one-dimensional array:
The program compares each student’s answers with the key, counts the number of correct
answers, and displays it
26/28
Problem: Grading a Multiple-Choice Test
public class GradeExam { /** Main method */
public static void main(String[] args) { // Students’ answers to the questions char[][] answers = {
{'A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}, {'D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'}, {'E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'}, {'C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'}, {'A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}, {'B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}, {'B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}, {'E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}};
// Key to the questions
char[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'};
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Problem: Grading a Multiple-Choice Test
// Grade all answers
for (int i = 0; i < answers.length; i++) { // Grade one student
int correctCount = 0;
for (int j = 0; j < answers[i].length; j++) { if(answers[i][j] == keys[j])
correctCount++;
}
System.out.println("Student " + i+ "’s correct count is " + correctCount);
} } }
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Output
27/28
Passing Two-Dimensional Arrays to Methods
You can pass a two-dimensional array to a method just as you pass a one-dimensional array.
Example program with a method that returns the sum of all the elements in a matrix.
import java.util.Scanner;
public class PassTwoDimensionalArray { public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Enter array values int[][] m = new int[3][4];
System.out.println("Enter " + m.length + " rows and "
+ m[0].length + " columns: ");
for (int i = 0; i < m.length; i++) for (int j = 0; j < m[i].length; j++)
m[i][j] = input.nextInt();
// Display result
System.out.println("\nSum of all elements is " + sum(m));
} Java Programming - Prof. Moheb Ramzy Girgis
Dept. of Computer Science - Faculty of Science Minia University
Passing Two-Dimensional Arrays to Methods
// A method that returns sum of all the elements in a matrix.
public static int sum(int[][] m) { int total = 0;
for (int row = 0; row < m.length; row++) {
for (int column = 0; column < m[row].length; column++) { total += m[row][column];
} }
return total;
} }
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Output
28/28
Multidimensional Arrays
Occasionally, you will need to represent n-dimensional data structures. In Java, you can create n-dimensional arrays for any integer n.
The way to declare two-dimensional array variables and create two-dimensional arrays can be generalized to declare n-dimensional array variables and create n-dimensional arrays for n ≥ 3.
For example, the following syntax declares a three-
dimensional array variable scores, creates an array, and assigns its reference to scores.
double[][][] scores = new double[10][24][2];
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University
Multidimensional Arrays
A multidimensional array is actually an array in which each element is another array.
A three dimensional array consists of an array of two- dimensional arrays, each of which is an array of one- dimensional arrays.
For example, suppose x = new int[2][2][5], x[0] and x[1] are two-dimensional arrays.
X[0][0], x[0][1], x[1][0], and x[1][1] are one dimensional arrays and each contains five elements.
x.length is 2, x[0].length and x[1].length are 2, and
X[0][0].length, x[0][1].length, x[1][0].length, and x[1][1].length are 5.
Java Programming - Prof. Moheb Ramzy Girgis Dept. of Computer Science - Faculty of Science
Minia University