2D Arrays
A two-dimensional array is a data structure in Java that is an array of arrays. Each element in the array is an array itself. Generally, a two-dimensional array is referred to be columns and rows:
Initializing a Two-Dimensional Array
-
int[][] myArray = new int [3][4];
- This initializes a 2D array with 3 rows and 4 columns. -
The
new
keyword is used to allocate memory space for a new 2D array. -
Using an initializer list:
int[][] myArray = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
Rows are the elements in an array that it can store horizontally. row size equal to 2 will create 2 rows. Columns are the elements in an array that it can store vertically.
Examples
Adding Elements in a 2D Array
To add elements to a 2D array, we specify the index values for the row and column where we want to insert the element.
int[][] sampleArray = new int[2][2];
sampleArray[0][0] = 0;
sampleArray[0][1] = 1;
sampleArray[1][0] = 2;
sampleArray[1][1] = 3;
Modifying Elements in a 2D Array
To modify an element in a 2D array, we specify the index values for the row and column we want to modify and assign the new value.
int[][] sampleArray = new int[2][2];
sampleArray[0][1] = 10;
Row-Major Traversal of a 2D Array
Row-major order is one of two common ways to traverse through a 2D array. We access each element in a row before moving on to the next row.
int[][] numbers = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8} };
for (int row = 0; row < numbers.length; row++) {
for (int col = 0; col < numbers[0].length; col++) {
System.out.print(numbers[row][col] + " ");
}
System.out.println();
}
Output:
0 1 2
3 4 5
6 7 8
Column-Major Traversal of a 2D Array
Column-major order is one of two common ways to traverse through a 2D array. We access each element in a column before moving on to the next column.
int[][] numbers = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8} };
for (int col = 0; col < numbers[0].length; col++) {
for (int row = 0; row < numbers.length; row++) {
System.out.print(numbers[row][col] + " ");
}
System.out.println();
}
Output:
0 3 6
1 4 7
2 5 8
Traversing 2D Arrays with Enhanced for Loops
When traversing a 2D array with enhanced for
loops, the outer loop refers to each row while the inner loop refers to each element in the current row.
int[][] numbers = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8} };
for (int[] currentRow: numbers) {
for (int value: currentRow) {
System.out.println(value);
}
}
Syntax
int[][] test = new int[4][4];