You are on page 1of 3

2D Array

If 1D arrays are thought of as list, then 2D arrays can be thought of as tables. In


Java, 2D arrays are implemented as an array of arrays.

e.g.

// constant for capacity


final int MAXROWS = 3;
final int MAXCOLS = 2

//1. declare a variable of the array class to store integers


int[][] table;

//2. instantiate an instance of the class specifying a capacity of 3


elements in a row, and 2 elements in a column
table = new int[MAXROWS][MAXCOLS];

The 2D array created above has 3 rows and two columns. It is represented as
an array of 3 arrays of size 2. Therefore table.length will return 3 (number of
arrays), and table[0].length will return 2 (number of elements in the first
array)

Abstractly, the above arrays can be visualize as the following:

table[0][0] table[0][1]
table[1][0] table[1][1]
table[2][0] table[2][1]

The index of each element has two components: [row number][column number].
Note that, same as 1D array, index starts with 0.

A 2D array is an array of array. It is represented in the memory as follows:

1 3 table
2
3 6 table[0]
4 8 table[1]
5 10 table[2]
6 table[0][0]
7 table[0][1]
8 table[1][0]
9 table[1][1]
10 table[2][0]
11 table[2][1]
Since each element has two indices, in order to loop through each row, and each
column, a two level nested loop is required.

e.g.
Using a 2D array to store a set of five test marks for each of 4 students. Ask the
user to enter each mark and store it in corresponding location.

You can think of the table as below:


Test
0 1 2 3 4
0
Students

1
2
3

// constant for capacity


final int MAXSTUDS = 4;
final int MAXTESTS = 5;

//1. declare a variable of the array class to store double


double[][] marks;

//2. instantiate an instance of the class specifying a capacity of 4


// rows, and 5 columns
marks = new double[MAXSTUDS][MAXTESTS];

// ask user for the mark


for (int j = 0; j < MAXSTUDS; j++) {
System.out.println(Marks of student + j);
for (int k = 0; k < MAXTESTS; k++) {
System.out.print(Test # + k);
marks[j][k] = sc.nextDouble();
}
}

A 2D array can be initialized with values, just like a 1D array:

String cartoons [][]=


{
{ "Flintstones", "Fred", "Wilma", "Pebbles", "Dino" },
{ "Rubbles", "Barney", "Betty", "Bam Bam" },
{ "Jetsons", "George", "Jane", "Elroy", "Judy"},
{ "Scooby Doo", "Shaggy", "Velma", "Fred", "Daphne" }
};

The above code automatically creates an array with 4 rows and 5


columns and fill in the content accordingly. If you want to print
out the content of the array, try the following code:

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


{
for (int j = 0 ; j < cartoons [i].length ; j++)
{
System.out.print (cartoons [i] [j] + " ");
}
System.out.println ();
}

You might also like