<< Chapter < Page | Chapter >> Page > |
fib
of type integer array is allocated. As part of the same statement, the array object is created with its seven fields having the values in the initializer; the reference to the object is returned and stored in the variable
fib
.first
. The formal parameter
a
contains a reference to the same array pointed to by the actual parameter
fib
.b
of the same type as the parameter
a
but half the length is declared and allocated.a
to the corresponding element in the array
b
.b
is returned. Although array referenced by
b
was allocated
within the method call, it still exists after returning.Exercise Modify the program so that the original array remains accessible in a different field.
Concept A matrix can be stored in a two-dimensional array. The syntax is
int[][]
with two indices, the first for rows and the second for
columns. To access an element of the array, expressions for the twoindices must be givien.
Program: Array06.java
// Learning Object Array06
// two-dimensional arrayspublic class Array06 {
static int addElements(int[][] a) { int sum = 0;
for (int i = 0; i < a.length; i++)
for (int j = 0; j < a[i].length; j++) sum = sum + a[i][j];
return sum; }
public static void main(/*String[] args*/) { int[][] matrix = new int[2][2];
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++) matrix[i][j] = i*matrix.length + j;
int sum = addElements(matrix); }
}
This program creates a matrix and computes the sum of its elements.
matrix
.
The variable
matrix
contains one reference for each row,
and the rows are allocated as separate objects.Note that Jeliot displays each row from top to bottom as it does for all objects!matrix.length
is used to get the number of rows and
matrix[i].length
to get the number of columns in row
i
, which
is the same for all rows in this program.addElements
, which adds the values of all the elements.sum
.Exercise Modify the program perform the same computation on a matrix and on a matrix.
Concept A two-dimensional array is really an array of arrays; that is, each element of the array contains a reference to another array. Therefore, byusing only one index a one-dimensional array is obtained.
Notification Switch
Would you like to follow the 'Learning objects for java (with jeliot)' conversation and receive update notifications?