How do 2D arrays work in Java, and what is really going on when you write int[][] grid?
A two dimensional array in Java is really an array of arrays. When you write int[][] grid, you are declaring a variable that holds a reference to an array, and every element of that array is itself a reference to another array.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Three rows, and four columns in each row.
int[][] grid = new int[3][4];
for (int row = 0; row < grid.length; row++) {
for (int column = 0; column < grid[row].length; column++) {
grid[row][column] = row * 10 + column;
}
}
System.out.println("rows : " + grid.length);
System.out.println("columns : " + grid[0].length);
System.out.println("cell : " + grid[1][2]);
System.out.println("row two : " + Arrays.toString(grid[1]));
}
}
So what is really going on when you write new int[3][4]? The language makes one array of three references, and then it makes a separate array of four int values for each of those three, and it points each reference at one of them.
Two consequences follow from that, and both of them bite people.
The first one is that the rows do not have to be the same length. Each row is its own array, so one row can have four values and the next can have two. This is why you should always ask grid[row].length for the number of columns in a row, rather than assuming a number that you wrote down earlier.
The second one is that every value starts at zero. Java fills a new array of numbers with zeros, and it fills a new array of objects with null, so you have to fill in the objects yourself.
The next question in this topic looks at what happens when you leave out the second size.