Arrays
Two-dimensional arrays
Rectangular
How to work with rectangular arrays
- Two-dimensional arrays use two indexes and allow data to be stored in a table that consists of rows and columns.
- This can also be thought of as an array of arrays where each row is a separate array of columns.
- A rectangular array is a two-dimensional array whose rows all have the same number of columns.
How to create a rectangular array
The syntax for creating a rectangular array type[][] arrayName = new type[rowCount][columnCount]; A statement that creates a 3x2 array int[][] numbers = new int[3][2];
How to assign values to a rectangular array
The syntax for referring to an element of a rectangular array
arrayName[rowIndex][columnIndex]
The indexes for a 3x2 array
[0][0] [0][1]
[1][0] [1][1]
[2][0] [2][1]
Code that assigns values to the array
numbers[0][0] = 1;
numbers[0][1] = 2;
numbers[1][0] = 3;
numbers[1][1] = 4;
numbers[2][0] = 5;
numbers[2][1] = 6;
Code that creates a 3x2 array and initializes it in one statement
int[][] numbers = { {1,2} {3,4} {5,6} };
Code that processes a rectangular array with nested for loops
int[][] numbers = { {1,2}, {3,4}, {5,6} };
for (int i = 0; i < numbers.length; i++)
{
for (int j = 0; j < numbers[i].length; j++)
System.out.print(numbers[i][j] + " ");
System.out.print("\n");
}
The console output
1 2 3 4 5 6