Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
45 views

Arrays in Java

1. The document discusses arrays in Java, including how to declare, create, initialize, access elements of, and process arrays. 2. Arrays allow storing multiple values in a single variable and accessing them via indexes. An array is declared with the element type and size, and memory is allocated using new. 3. Elements can be accessed and assigned using indexes from 0 to length-1. Arrays can also be initialized in a single statement using array initializers.

Uploaded by

rbnnamisi941
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Arrays in Java

1. The document discusses arrays in Java, including how to declare, create, initialize, access elements of, and process arrays. 2. Arrays allow storing multiple values in a single variable and accessing them via indexes. An array is declared with the element type and size, and memory is allocated using new. 3. Elements can be accessed and assigned using indexes from 0 to length-1. Arrays can also be initialized in a single statement using array initializers.

Uploaded by

rbnnamisi941
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

School of Computing and Informatics

BCS 210 – Object Oriented Programming


Single-Dimensional Two-Dimensional Arrays

R
1 Introduction
A single array variable can reference a large collection of data.

LU
Often you will have to store a large number of values during the execution of a program. Suppose, for
instance, that you need to read 100 numbers, compute their average, and find out how many numbers are
above the average. Your program first reads the numbers and computes their average, then compares each
number with the average to determine whether it is above the average. In order to accomplish this task,
the numbers must all be stored in variables. You have to declare 100 variables and repeatedly write almost
U
identical code 100 times. Writing a program this way would be impractical. So, how do you solve this
problem?
G
An efficient, organized approach is needed. Java and most other high-level languages provide a data struc-
ture, the array, which stores a fixed-size sequential collection of elements of the same type. In the present
case, you can store all 100 numbers into an array and access them through a single array variable
N

2 Array Basics
.A

Once an array is created, its size is fixed. An array reference variable is used to access the elements in an
array using an index.

An array is used to store a collection of data, but often we find it more useful to think of an array as
a collection of variables of the same type. Instead of declaring individual variables, such as number0,
R

number1, . . . , and number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], . . . , and numbers[99] to represent individual variables. This section introduces how to
declare array variables, create arrays, and process arrays using indexes.
D

2.1 Declaring Array Variables


To use an array in a program, you must declare a variable to reference the array and specify the arrays
element type. Here is the syntax for declaring an array variable:
1 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.
1 double[ ] myList;

Dr. Raphael Angulu, BCS210 SCI, MMUST, 2020: Arrays in Java Notes 1
You can also use elementType arrayRefVar[ ] to declare an array variable. This style comes from the
C/C++ language and was adopted in Java to accommodate C/C++ programmers. The style element-
Type[ ] arrayRefVar is preferred.

2.2 Creating Arrays


Unlike declarations for primitive data type variables, 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. 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 new operator and assign its reference to the variable with the following syntax:
1 arrayRefVar = new elementType[arraySize];

This statement does two things: (1) it creates an array using new elementType[arraySize]; (2) it assigns
the reference of the newly created array to the variable arrayRefVar.

R
Declaring an array variable, creating an array, and assigning the reference of the array to the variable
can be combined in one statement as:
1 elementType[ ] arrayRefVar = new elementType[arraySize];

LU
or
1 elementType arrayRefVar[] = new elementType[arraySize];

Here is an example of such a statement:


1 double[ ] myList = new double[10];
U
This statement declares an array variable, myList, creates an array of ten elements of double type, and
assigns its reference to myList. To assign values to the elements, use the syntax:
G
1 arrayRefVar[index] = value;

For example, the following code initializes the array


myList[0] = 5.6;
N

1
2 myList[1] = 4.5;
3 myList[2] = 3.3;
4 myList[3] = 13.2;
.A

5 myList[4] = 4.0;
6 myList[5] = 34.33;
7 myList[6] = 34.0;
8 myList[7] = 45.45;
9 myList[8] = 99.993;
10 myList[9] = 11123;
R

This array is illustrated in Figure 1 An array variable that appears to hold an array actually contains a
D

Figure 1: The array myList has ten elements of double type and int indices from 0 to 9

Dr. Raphael Angulu, BCS210 SCI, MMUST, 2020: Arrays in Java Notes 2
reference to that array. Strictly speaking, an array variable and an array are different, but most of the time
the distinction can be ignored. Thus it is all right to say, for simplicity, that myList is an array, instead
of stating, at greater length, that myList is a variable that contains a reference to an array of ten double
elements.

2.3 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, \u0000 for char types, and false for boolean types.

R
2.4 Accessing Array Elements
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 Figure 1, myList holds ten double values, and the indices
are from 0 to 9.

LU
Each element in the array is represented using the following syntax, known as an indexed variable:
1 arrayRefVar[index];

For example, myList[9] represents the last element in the array myList. An indexed variable can be used
in the same way as a regular variable. For example, the following code adds the values in myList[0] and
U
myList[1] to myList[2]
1 myList[2] = myList[0] + myList[1];
G
The following loop assigns 0 to myList[0], 1 to myList[1], . . . , and 9 to myList[9]:
1 for ( int i = 0; i < myList.length; i++) {
2 myList[i ] = i;
}
N

2.5 Array Initializers


.A

Java has a shorthand notation, known as the array initializer, which combines the declaration, creation, and
initialization of an array in one statement using the following syntax:
1 elementType[ ] arrayRefVar = {value0, value1, ..., valuek};

For example, the statement


R

1 double[ ] myList = {1.9, 2.9, 3.4, 3.5};

declares, creates, and initializes the array myList with four elements, which is equivalent to the following
statements:
D

1 double[] myList = new double[4];


2 myList[0] = 1.9;
3 myList[1] = 2.9;
4 myList[2] = 3.4;
5 myList[3] = 3.5;

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:
1 double[] myList;
2 myList = {1.9, 2.9, 3.4, 3.5};

Dr. Raphael Angulu, BCS210 SCI, MMUST, 2020: Arrays in Java Notes 3
2.6 Processing Arrays
When processing array elements, you will often use a for loopfor 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:


1 double[ ] myList = new double[10];

The following are some examples of processing arrays.

1. Initializing arrays with input values: The following loop initializes the array myList with user
input values.

R
1 java . util .Scanner input = new java.util.Scanner(System.in);
2 System.out.print(”Enter ” + myList.length + ” values: ”);
3 for ( int i = 0; i < myList.length; i++)
4 myList[i ] = input.nextDouble();

LU
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
1 for ( int i = 0; i < myList.length; i++) {
2 myList[i ] = Math.random() ∗ 100;
3 }
U
3. Displaying arrays: To print an array, you have to print each element in the array using a loop like
the following:
G
1 for ( int i = 0; i < myList.length; i++) {
2 System.out.print(myList[i] + ” ”);
3 }
N

For an array of the char[] type, it can be printed using one print statement. For example, the following
code displays Dallas:
.A

1 char[ ] city = {’D’, ’a’ , ’ l ’ , ’ l ’ , ’a’ , ’ s ’ };


2 System.out.println( city ) ;

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:
double total = 0;
R

1
2 for ( int i = 0; i < myList.length; i++) {
3 total += myList[i];
4 }
D

5. Finding the largest element: Use a variable named max to 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.
1 double max = myList[0];
2 for ( int i = 1; i < myList.length; i++) {
3 if (myList[i ] > max) max = myList[i];
4 }

Dr. Raphael Angulu, BCS210 SCI, MMUST, 2020: Arrays in Java Notes 4
6. Finding the smallest index of the largest element: Often you need to locate the largest element
in an array. If an array has multiple elements with the same largest value, 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 max to store the largest element and a variable
named indexOfMax to denote the index of the largest element. Initially max is myList[0], and
indexOfMax is 0. Compare each element in myList with max, and update max and indexOfMax
if the element is greater than max.
1 double max = myList[0];
2 int indexOfMax = 0;
3 for ( int i = 1; i < myList.length; i++) {
4 if (myList[i ] > max) {
5 max = myList[i];
6 indexOfMax = i;
7 }
8 }

R
7. Random shuffling: In many applications, you need to randomly reorder the elements in an array.
This is called shuffling. To accomplish this, for each element myList[i], randomly generate an index
j and swap myList[i] with myList[j], as follows:

LU
1 for ( int i = myList.length 1; i > 0; i ) {
2 // Generate an index j randomly with 0 <= j <= i
3 int j = (int)(Math.random() ∗ (i + 1));
4 // Swap myList[i] with myList[j]
5 double temp = myList[i];
6 myList[i ] = myList[j];
7 myList[j] = temp;
U
8 }

8. Shifting elements: Sometimes you need to shift the elements left or right. Here is an example of
G
shifting the elements one position to the left and filling the last element with the first element:
1 double temp = myList[0]; // Retain the first element
2 // Shift elements left
N

3 for ( int i = 1; i < myList.length; i++) {


4 myList[i − 1] = myList[i];
5 }
6 // Move the first element to fill in the last position
.A

7 myList[myList.length − 1] = temp;

9. Simplifying coding: Arrays can be used to greatly simplify coding for certain tasks. For example,
suppose you wish to obtain the English name of a given month by its number. If the month names
are stored in an array, the month name for a given month can be accessed simply via the index. The
R

following code prompts the user to enter a month number and displays its month name:
1 String [] months = {”January”, ”February”, ..., ”December”};
2 System.out.print(”Enter a month number (1 to 12): ”);
D

3 int monthNumber = input.nextInt();


4 System.out.println(”The month is ” + months[monthNumber − 1]);

If you didnt use the months array, you would have to determine the month name using a lengthy
multi-way if-else statement as follows:
1 if (monthNumber == 1)
2 System.out.println(”The month is January”);
3 else if (monthNumber == 2)
4 System.out.println(”The month is February”);
5 ...
6 else
7 System.out.println(”The month is December”);

Dr. Raphael Angulu, BCS210 SCI, MMUST, 2020: Arrays in Java Notes 5
2.7 Foreach Loops
Java supports a convenient for loop, known as a foreach 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:
1 for (double e: myList) {
2 System.out.println(e) ;
3 }

You can read the code as for each element e in myList, do the following. Note that the variable, e, must be
declared as the same type as the elements in myList.

In general, the syntax for a foreach loop is


1 for (elementType element: arrayRefVar) {
2 // Process the element

R
3 }

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

LU
3 Copying Arrays
To copy the contents of one array into another, you have to copy the arrays individual elements into the
other array.
U
Often, in a program, you need to duplicate an array or a part of an array. In such cases you could at-
tempt to use the assignment statement (=), as follows:
1 list2 = list1 ;
G
However, this statement does not copy the contents of the array referenced by list1 to list2, but instead
merely copies the reference value from list1 to list2. After this statement, list1 and list2 reference the
same array, as shown in Figure 2.
N
.A
R

Figure 2: Before the assignment statement, list1 and list2 point to separate memory locations. After the
assignment, the reference of the list1 array is passed to list2.
D

The array previously referenced by list2 is no longer referenced; it becomes garbage, which will be auto-
matically collected by the Java Virtual Machine (this process is called garbage collection).

In Java, you can use assignment statements to copy primitive data type variables, but not arrays. As-
signing one array variable to another array variable actually copies one reference to another and makes both
variables point to the same memory location.

There are three ways to copy arrays

• Use a loop to copy individual elements one by one.

Dr. Raphael Angulu, BCS210 SCI, MMUST, 2020: Arrays in Java Notes 6
• Use the static arraycopy method in the System class.

• Use the clone method to copy arrays (we will not discuss this now)

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.
1 int [] sourceArray = {2, 3, 1, 5, 10};
2 int [] targetArray = new int[sourceArray.length];
3 for ( int i = 0; i < sourceArray.length; i++) {
4 targetArray[i ] = sourceArray[i];
5 }

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:
1 arraycopy(sourceArray, srcPos, targetArray, tarPos, length) ;

R
The arraycopy method does not allocate memory space for the target array. The target array must have
already been created with its memory space allocated. After the copying takes place, targetArray and
sourceArray have the same content but independent memory locations.

LU
Note: The arraycopy method violates the Java naming convention. By convention, this method should
be named arrayCopy

4 Passing Arrays to Methods


When passing an array to a method, the reference of the array is passed to the method .
U
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:
G
1 public static void printArray(int [] array) {
2 for ( int i = 0; i < array.length; i++) {
3 System.out.print(array[ i ] + ” ”);
N

4 }
5 }

You can invoke it by passing an array. For example, the following statement invokes the printArray method
.A

to display 3, 1, 2, 6, 4, and 2.
1 printArray(new int []{3, 1, 2, 6, 4, 2});

Note: The preceding statement creates an array using the following syntax:
1 new elementType[]{value0, value1, ..., valuek};
R

There is no explicit reference variable for the array. Such array is called an anonymous array.

Java uses pass-by-value to pass arguments to a method. There are important differences between pass-
D

ing the values of variables of primitive data types and passing arrays.

• For an argument of a primitive type, the arguments value is passed.

• For an argument of an array type, the value of the argument is a reference to an array; this reference
value is passed to the method. Semantically, it can be best described as pass-by-sharing, that is, the
array in the method is the same as the array being passed. Thus, if you change the array in the
method, you will see the change outside the method.

Note: Arrays are objects in Java. The JVM stores the objects in an area of memory called the heap, which
is used for dynamic memory allocation.

Dr. Raphael Angulu, BCS210 SCI, MMUST, 2020: Arrays in Java Notes 7
5 Returning an Array from a Method
When a method returns an array, the reference of the array is returned

You can pass arrays when invoking a method. A method may also return an array. For example, the
following method returns an array that is the reversal of another array.
1 public static int [] reverse ( int [] list ) {
2 int [] result = new int[ list .length ];
3 for ( int i = 0, j = result .length − 1;i < list .length; i++, j−−) {
4 result [ j ] = list [ i ];
5 }
6 return result ;
7 }

Line 2 creates a new array result. Lines 47 copy elements from array list to array result. Line 9 returns the
array. For example, the following statement returns a new array list2 with elements 6, 5, 4, 3, 2, 1.

R
1 int [] list1 = {1, 2, 3, 4, 5, 6};
2 int [] list2 = reverse( list1 ) ;

LU
6 Variable-Length Argument List
A variable number of arguments of the same type can be passed to a method and treated as an array

You can pass a variable number of arguments of the same type to a method. The parameter in the method
is declared as follows:
U
1 typeName...parameterName

In the method declaration, you specify the type followed by an ellipsis (...). Only one variable-length param-
G
eter may be specified in a method, and this parameter must be the last parameter. Any regular parameters
must precede it.
N

Java treats a variable-length parameter as an array. You can pass an array or a variable number of ar-
guments to a variable-length parameter. When invoking a method with a variable number of arguments,
Java creates an array and passes the arguments to it.
.A

Listing 1 contains a method that prints the maximum value in a list of an unspecified number of values.
1 public class VarArgsDemo {
2 public static void main(String[] args) {
3 printMax(34, 3, 3, 2, 56.5) ;
4 printMax(new double[]{1, 2, 3});
R

5 }
6 public static void printMax(double... numbers) {
7 if (numbers.length == 0) {
System.out.println(”No argument passed”);
D

8
9 return;
10 }
11 double result = numbers[0];
12 for ( int i = 1; i < numbers.length; i++){
13 if (numbers[i] > result)
14 result = numbers[i];
15 }
16 System.out.println(”The max value is ” + result);
17 }
18 }

Listing 1: Variable Length Demo

Dr. Raphael Angulu, BCS210 SCI, MMUST, 2020: Arrays in Java Notes 8
Line 3 and 4 in Listing 1 shows how a variable length argument can be passed to a method. Note that,
calling the method as
1 printMax(new int[]{1, 4, 6, 12});

will result into an error since the type of passed arguments (int) does not match declared parameter at
method header at line 6 (double)

7 Two-Dimensional Arrays
Data in a table or a matrix can be represented using a two-dimensional array.

You can use a two-dimensional array to store a matrix or a table. For example, the following table that lists
the distances between cities can be stored using a two-dimensional array named distances.

R
LU
U
1 double [][] distances = {
2 {0, 983, 787, 714, 1375, 967, 1087},
3 {983, 0, 214, 1102, 1763, 1723, 1842},
4 {787, 214, 0, 888, 1549, 1548, 1627},
G
5 {714, 1102, 888, 0, 661, 781, 810},
6 {1375, 1763, 1549, 661, 0, 1426, 1187},
7 {967, 1723, 1548, 781, 1426, 0, 239},
{1087, 1842, 1627, 810, 1187, 239, 0},
N

8
9 };
.A

7.1 Two-Dimensional Array Basics


An element in a two-dimensional array is accessed through a row and column index.

How do you declare a variable for two-dimensional arrays? How do you create a two-dimensional array?
How do you access elements in a two-dimensional array? This section addresses these issues.
R

7.1.1 Declaring Variables of Two-Dimensional Arrays and Creating Two-Dimensional Arrays


D

The syntax for declaring a two-dimensional array is:


1 elementType[][] arrayRefVar;

or
1 elementType arrayRefVar[][]; // Allowed, but not preferred

As an example, here is how you would declare a two-dimensional array variable matrix of int values:
1 int [][] matrix;

or
1 int matrix [][]; // This style is allowed, but not preferred

Dr. Raphael Angulu, BCS210 SCI, MMUST, 2020: Arrays in Java Notes 9
You can create a two-dimensional array of 5-by-5 int values and assign it to matrix using this syntax:
1 matrix = new int [5][5];

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 int type and starts from 0, as shown in Figure
3(a). To assign the value 7 to a specific element at row 2 and column 1, as shown in Figure 3(b), you can

R
Figure 3: The index of each subscript of a two-dimensional array is an int value, starting from 0, to rows-1

LU
and cols-1

use the following syntax:


1 matrix [2][1] = 7;

Caution: It is a common mistake to use matrix[2, 1] to access the element at row 2 and column 1. In
U
Java, each subscript must be enclosed in a pair of square brackets.

You can also use an array initializer to declare, create, and initialize a two-dimensional array. For ex-
G
ample, the following code in (a) creates an array with the specified initial values, as shown in Figure 3(c).
This is equivalent to the code in (b).
N
.A
R

7.1.2 Obtaining the Lengths of Two-Dimensional Arrays


D

A two-dimensional array is actually an array in which each element is a one-dimensional array. The length
of an array x is the number of elements in the array, which can be obtained using x.length.

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], therefore, x[0], x[1], and x[2] are one-dimensional arrays and
each contains four elements, as shown in Figure 4. x.length is 3 (number of rows), and x[0].length,
x[1].length, and x[2].length are 4 (number of elements in each row).

Dr. Raphael Angulu, BCS210 SCI, MMUST, 2020: Arrays in Java Notes 10
Figure 4: A two-dimensional array is a one-dimensional array in which each element is another one-
dimensional array

7.1.3 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. Here is an example of creating a ragged array: As you can

R
LU
see, triangleArray[0].length is 5, triangleArray[1].length is 4, triangleArray[2].length is 3, trian-
U
gleArray[3].length is 2, and triangleArray[4].length is 1.

If you dont know the values in a ragged array in advance, but do know the sizessay, the same as beforeyou
G
can create a ragged array using the following syntax:
1 int [][] triangleArray = new int [5][];
triangleArray [0] = new int[5];
N

2
3 triangleArray [1] = new int[4];
4 triangleArray [2] = new int[3];
5 triangleArray [3] = new int[2];
.A

6 triangleArray [4] = new int[1];

You can now assign values to the array. For example,


1 triangleArray [0][3] = 50;
2 triangleArray [4][0] = 45;

Note: The syntax new int[5][] for creating an array requires the first index to be specified. The syntax
R

new int[][] would be wrong

7.2 Processing Two-Dimensional Arrays


D

Nested for loops are often used to process a two-dimensional array..

Suppose an array matrix is created as follows:


1 int [ ][ ] matrix = new int [10][10];

The following are some examples of processing two-dimensional arrays.

1. Initializing arrays with input values. The following loop initializes the array with user input
values:

Dr. Raphael Angulu, BCS210 SCI, MMUST, 2020: Arrays in Java Notes 11
1 java . util .Scanner input = new Scanner(System.in);
2 System.out.println(”Enter ” + matrix.length + ” rows and ” +
3 matrix [0]. length + ” columns: ”);
4 for ( int row = 0; row < matrix.length; row++) {
5 for ( int column = 0; column < matrix[row].length; column++) {
6 matrix[row][column] = input.nextInt();
7 }
8 }

2. Initializing arrays with random values. The following loop initializes the array with random
values between 0 and 99
1 for ( int row = 0; row < matrix.length; row++) {
2 for ( int column = 0; column < matrix[row].length; column++) {
3 matrix[row][column] = (int)(Math.random() ∗ 100);
4 }
5 }

R
3. Printing arrays. To print a two-dimensional array, you have to print each element in the array using
a loop like the following
1 for ( int row = 0; row < matrix.length; row++) {

LU
2 for ( int column = 0; column < matrix[row].length; column++) {
3 System.out.print(matrix[row][column] + ” ”);
4 }
5 System.out.println() ;
6 }
U
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:
1 int total = 0;
G
2 for ( int row = 0; row < matrix.length; row++) {
3 for ( int column = 0; column < matrix[row].length; column++) {
4 total += matrix[row][column];
5 }
N

6 }

5. Summing elements by column. For each column, use a variable named total to store its sum.
.A

Add each element in the column to total using a loop like this:
1 for ( int column = 0; column < matrix[0].length; column++) {
2 int total = 0;
3 for ( int row = 0; row < matrix.length; row++)
4 total += matrix[row][column];
5 System.out.println(”Sum for column ” + column + ” is ” + total);
R

6 }

6. Random shuffling. How do you shuffle all the elements in a two-dimensional array? To accomplish
D

this, for each element matrix[i][j], randomly generate indices i1 and j1 and swap matrix[i][j] with
matrix[i1][j1], as follows:
1 for ( int i = 0; i < matrix.length; i++) {
2 for ( int j = 0; j < matrix[i ]. length; j++) {
3 int i1 = (int)(Math.random() ∗ matrix.length);
4 int j1 = (int)(Math.random() ∗ matrix[i].length);
5 // Swap matrix[i][ j ] with matrix[i1 ][ j1 ]
6 int temp = matrix[i][j ];
7 matrix[i ][ j ] = matrix[i1 ][ j1 ];
8 matrix[i1 ][ j1 ] = temp;
9 }
10 }

Dr. Raphael Angulu, BCS210 SCI, MMUST, 2020: Arrays in Java Notes 12
7. 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 index-
OfMaxRow if the new sum is greater
1 int maxRow = 0;
2 int indexOfMaxRow = 0;
3 // Get sum of the first row in maxRow
4 for ( int column = 0; column < matrix[0].length; column++) {
5 maxRow += matrix[0][column];
6 }
7 for ( int row = 1; row < matrix.length; row++) {
8 int totalOfThisRow = 0;
9 for ( int column = 0; column < matrix[row].length; column++)
10 totalOfThisRow += matrix[row][column];
11 if (totalOfThisRow > maxRow) {
12 maxRow = totalOfThisRow;
13 indexOfMaxRow = row;

R
14 }
15 }
16 System.out.println(”Row ” + indexOfMaxRow + ” has the maximum sum of ” + maxRow);

7.3 Passing Two-Dimensional Arrays to Methods

LU
When passing a two-dimensional array to a method, the reference of the array is passed to the method .

You can pass a two-dimensional array to a method just as you pass a one-dimensional array.
U
You can also return an array from a method. Listing 2 gives an example with two methods. The first
method, getMarks(), returns a two-dimensional array, and the second method, getSum(int[][] m), re-
turns the sum of all the elements in a matrix.
G
1 import java. util .Scanner
2 public class PassTwoDimensionalArrays {
3 public static int [][] getMarks(){ //read marks from the keyboard. Will return 2D array
4 Scanner input = new Scanner(System.in);
N

5 int [][] marks = new int[3][4]; //declare and create an array to hold marks of 3 students 4 subjects
6 System.out.println(”Enter Marks for” + marks.length + ” students and ” +
7 marks[0].length + ” subjects”);
for ( int i = 0; i < marks.length; i++){
.A

8
9 for ( int j = 0; j < marks[0].length; j++){
10 marks[i ][ j ] = input.nextInt();
11 }
12 }
13 return marks;
14 }
R

15 public static int getSum(int [][] m){ //we pass 2D array here
16 int sum = 0;
17 for ( int i = 0; i < m.length; i++){
18 for ( int j = 0; j < m[0].length; j++){
D

19 sum += m[i][j];
20 }
21 }
22 return sum;
23 }
24 public static void main(String[] args) {
25 int [][] a = getMarks();//get marks
26 //Display sum
27 System.out.println(”Sum of all marks = ” + getSum(a));
28 }
29 }

Listing 2: Passing and returning 2D arrays from a method

Dr. Raphael Angulu, BCS210 SCI, MMUST, 2020: Arrays in Java Notes 13
You can use the for-each loop also to process 2D arrays. See the code in Listing 3.
1 import java. util .Scanner;
2 public class PassTwoDimensionalArrays {
3 public static int [][] getMarks() //read marks from the keyboard
4 {
5 Scanner input = new Scanner(System.in);
6 //declare and create an array to hold marks of 3 students 4 subjects
7 int [][] marks = new int[3][4];
8 System.out.println(”Enter Marks for” + marks.length + ” students and ” +
9 marks[0].length + ” subjects”);
10 for ( int [] mark : marks) {
11 for ( int j = 0; j < marks[0].length; j++) {
12 mark[j] = input.nextInt();
13 }
14 }
15 return marks;
16 }

R
17 public static int getSum(int [][] m){
18 int sum = 0;
19 for ( int [] m1 : m) {
20 for ( int j = 0; j < m[0].length; j++) {
21 sum += m1[j];

LU
22 }
23 }
24 return sum;
25 }
26 public static void main(String[] args) {
27 int [][] a = getMarks();//get marks
28 //Display sum
U
29 System.out.println(”Sum of all marks = ” + getSum(a));
30 }
31 }
G
Listing 3: Passing and returning 2D arrays from a method

Line 10 can be read as: For every 1D array mark in 2D array marks
N

Line 19 can be read as: For every 1D array m1 in 2D array m


.A
R
D

Dr. Raphael Angulu, BCS210 SCI, MMUST, 2020: Arrays in Java Notes 14

You might also like