Declaring and Initializing 2D Arrays
Part of: 2D Array
What Is a 2D Array? A two-dimensional array stores data in a grid of rows and columns . In Java it is really an array of arrays : each element of the outer array is itself a one-dimensional array (a row). On the AP CSA exam you only deal with rectangular 2D arrays, where every row has the same number of columns. Declaration Syntax You declare a 2D array by writing the element type followed by two pairs of brackets, then create the grid with new: This makes a grid with 3 rows and 4 columns . Every slot starts at the default value for the type, 0 for int, 0.0 for double, false for boolean, and null for object types like String. Initializer Lists You can also build a 2D array with a nested initializer list , giving the values directly. The compiler counts the rows and columns for you: Accessing Elements You access a single cell with two indices : the first is the row, the second is the column. Both start at 0. - m[r][c] reads or writes the cell at row r, column c. - The first index selects the row, the second selects the column. Reversing them is a classic bug. Valid row indices run from 0 to numRows - 1, and valid column indices from 0 to numCols - 1. Going outside these bounds throw
Challenge: Read and Echo a Grid Cell