Learn Java - Two-Dimensional Arrays Cheatsheet - Codecademy
Learn Java - Two-Dimensional Arrays Cheatsheet - Codecademy
Two-Dimensional Arrays
Declaring 2D Arrays
In Java, 2D arrays are stored as arrays of arrays. Therefore, the way 2D arrays are int[][] twoDIntArray;
declared is similar 1D array objects. 2D arrays are declared by defining a data type
String[][] twoDStringArray;
followed by two sets of square brackets.
double[][] twoDDoubleArray;
Initializer Lists
In Java, initializer lists can be used to quickly give initial values to 2D arrays. This can be // Method one: declaring and intitializing at the same time
done in two different ways.
double[][] doubleValues = {{1.5, 2.6, 3.7}, {7.5, 6.4, 5.3},
1. If the array has not been declared yet, a new array can be declared and
initialized in the same step using curly brackets. {9.8, 8.7, 7.6}, {3.6, 5.7, 7.8}};
2. If the array has already been declared, the new keyword along with the data
type must be used in order to use an initializer list
// Method two: declaring and initializing separately:
String[][] stringValues;
stringValues = new String[][] {{"working", "with"}, {"2D",
"arrays"}, {"is", "fun"}};
doubleValues[2][2] = 100.5;
// This will change the value 7.6 to 100.5
Row-Major Order
“Row-major order” refers to an ordering of 2D array elements where traversal occurs for(int i = 0; i < matrix.length; i++) {
across each row - from the top left corner to the bottom right. In Java, row major
for(int j = 0; j < matrix[i].length; j++) {
ordering can be implemented by having nested loops where the outer loop variable
iterates through the rows and the inner loop variable iterates through the columns. System.out.println(matrix[i][j]);
Note that inside these loops, when accessing elements, the variable used in the outer }
loop will be used as the first index, and the inner loop variable will be used as the
}
second index.
Column-Major Order
“Column-major order” refers to an ordering of 2D array elements where traversal for(int i = 0; i < matrix[0].length; i++) {
occurs down each column - from the top left corner to the bottom right. In Java,
for(int j = 0; j < matrix.length; j++) {
column major ordering can be implemented by having nested loops where the outer
loop variable iterates through the columns and the inner loop variable iterates through System.out.println(matrix[j][i]);
the rows. Note that inside these loops, when accessing elements, the variable used in }
the outer loop will be used as the second index, and the inner loop variable will be
}
used as the first index.