2D Array
Listen to this study note
#AP Computer Science A Study Guide
#2D Arrays
š” A 2D array in Java is essentially an array of arrays, forming a table-like structure with rows and columns.
#Declaration and Initialization
-
Declaration: To declare a 2D array, you specify the data type, followed by two sets of square brackets (one for rows, one for columns), and the array name.
java int[][] matrix; // Declares a 2D array named 'matrix' to store integers
- **Initialization:** You can initialize a 2D array during declaration or later in your code.
java // Initializing during declaration int[][] table = { {1, 2, 3}, {4, 5, 6} };
// Initializing later int[][] grid = new int[3][4]; // Creates a 3x4 grid (3 rows, 4 columns)
<div data-custom-tag="common_mistake">
Forgetting to initialize a 2D array with 'new' when you are not providing initial values during the declaration.
</div>
### Accessing Elements
- **Indices:** Elements in a 2D array are accessed using two indices: row index and column index.
- **Zero-based indexing:** Like 1D arrays, indexing starts from 0. - **Syntax:** `arrayName[rowIndex][columnIndex]`
java int value = table[1][0]; // Accesses the element at row 1, column 0 (value would be 4)
<div data-custom-tag="common_mistake">
Mixing up row and column indices is a frequent error. Remember: `array[row][column]`.
</div>
### Iterating Through a 2D Array
- **Nested Loops:** The most common way to traverse a 2D array is using nested loops.
java public static void print2DArray(int[][] arr) { for (int row = 0; row < arr.length; row++) { for (int col = 0; col < arr[row].length; col++) { System.out.print(arr[row][col] + "
Continue your learning journey

How are we doing?
Give us your feedback and let us know how we can improve