Learn Java - Two-Dimensional Arrays Cheatsheet - Codecademy
Learn Java - Two-Dimensional Arrays Cheatsheet - Codecademy
Two-Dimensional Arrays
Nested Iteration Statements
In Java, nested iteration statements are iteration
statements that appear in the body of another iteration for(int outer = 0; outer < 3; outer++){
statement. When a loop is nested inside another loop, the System.out.println("The outer index
inner loop must complete all its iterations before the is: " + outer);
outer loop can continue. for(int inner = 0; inner < 4; inner++)
{
System.out.println("\tThe inner
index is: " + inner);
}
}
Declaring 2D Arrays
In Java, 2D arrays are stored as arrays of arrays.
Therefore, the way 2D arrays are declared is similar 1D int[][] twoDIntArray;
array objects. 2D arrays are declared by defining a data String[][] twoDStringArray;
type followed by two sets of square brackets. double[][] twoDDoubleArray;
doubleValues[2][3] = 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 across each row - from for(int i = 0; i < matrix.length; i++) {
the top left corner to the bottom right. In Java, row major for(int j = 0; j < matrix[i].length;
ordering can be implemented by having nested loops j++) {
where the outer loop variable iterates through the rows System.out.println(matrix[i][j]);
and the inner loop variable iterates through the columns.
}
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 occurs down each column - for(int i = 0; i < matrix[0].length; i++)
from the top left corner to the bottom right. In Java, {
column major ordering can be implemented by having for(int j = 0; j < matrix.length; j++)
nested loops where the outer loop variable iterates {
through the columns and the inner loop variable iterates
System.out.println(matrix[j][i]);
through 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.
Traversing With Enhanced For Loops
In Java, enhanced for loops can be used to traverse 2D
arrays. Because enhanced for loops have no index for(String[] rowOfStrings
variable, they are better used in situations where you only : twoDStringArray) {
care about the values of the 2D array - not the location of for(String s : rowOfStrings) {
those values System.out.println(s);
}
}