Java 2D Arrays: Definition, Initialization, and Traversal¶
1. What is a 2D Array?¶
A 2D array can be understood as an “array of arrays”. If a 1D array is “a row of data”, a 2D array is a “matrix” composed of multiple “rows of data” (e.g., tables or matrices in mathematics). For example, the scores of 3 subjects for 5 students in a class can be stored in a 2D array.
2. How to Define a 2D Array?¶
A 2D array is essentially an “array of arrays”. The declaration syntax is:
dataType[][] arrayName; // Recommended for clarity
// Equivalent alternative syntaxes:
dataType[] arrayName[];
dataType arrayName[][];
Example: Declare a 3x4 2D array (integer type):
int[][] scores; // Defines a 2D array of type int named 'scores'
3. How to Initialize a 2D Array?¶
Initialization assigns values to the array and has two methods: static initialization and dynamic initialization.
(1) Static Initialization (Direct Assignment)¶
If all element values are known, use nested braces to assign values directly:
// Syntax: dataType[][] arrayName = {{row1 elements}, {row2 elements}, ...};
int[][] scores = {
{90, 85, 95}, // Row 0: Scores of student 1
{88, 92, 89}, // Row 1: Scores of student 2
{76, 80, 78} // Row 2: Scores of student 3
};
Note: The number of elements in each row can vary (Java supports “jagged arrays”), e.g., {{1, 2}, {3}} is also valid.
(2) Dynamic Initialization (Specify Size First, Then Assign Values)¶
Declare the array and specify its row and column sizes first, then assign values to elements individually:
// Syntax: dataType[][] arrayName = new dataType[numberOfRows][numberOfColumns];
int[][] arr = new int[3][4]; // Defines a 3x4 2D array; all elements default to 0
// Assign values to elements (by row/column index)
arr[0][0] = 10; // Row 0, Column 0
arr[0][1] = 20; // Row 0, Column 1
arr[1][2] = 30; // Row 1, Column 2
4. How to Traverse a 2D Array?¶
Traversing a 2D array requires nested loops (outer loop controls “rows”, inner loop controls “columns”).
(1) Traversal with Traditional for Loop (Nested Loops)¶
The outer loop controls the “row” (index i from 0 to row count - 1), and the inner loop controls the “column” (index j from 0 to column count - 1). Access elements via arr[i][j]:
int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Outer loop: control row count (i ranges from 0 to arr.length - 1)
for (int i = 0; i < arr.length; i++) {
// Inner loop: control column count (j ranges from 0 to arr[i].length - 1)
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println(); // New line to separate rows
}
Output:
1 2 3
4 5 6
7 8 9
(2) Traversal with Enhanced for Loop (foreach)¶
The outer loop iterates over “each row” (treating the 2D array as an array of rows), and the inner loop iterates over “each element in the row”. This is more concise:
int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Outer loop: iterate over each row (row is an int[] type)
for (int[] row : arr) {
// Inner loop: iterate over each element in the row (num is a single element)
for (int num : row) {
System.out.print(num + " ");
}
System.out.println(); // New line
}
Output is the same as above, but the code is more concise, suitable for scenarios where index modification is unnecessary.
5. Why Are 2D Arrays “Simpler Than 1D Arrays”?¶
- Essentially Simple: A 2D array can be viewed as a “collection of 1D arrays”. Its operation logic is “process rows first, then columns”, which aligns with the mathematical concept of matrices, making it more intuitive for beginners.
- Controllable Complexity: After mastering 1D arrays, 2D arrays only require adding one more nested loop. The structure is similar to “double nested loops”, which has a low learning curve.
- Clear Application Scenarios: 2D arrays are naturally suitable for storing tabular data (e.g., student grade tables, class seating charts) without needing to define complex structures.
Summary¶
The core of a 2D array is “an array of arrays”. Mastery requires understanding definition, initialization, and nested traversal. By extending the 1D array’s loop logic, 2D arrays can be easily handled by “outer loop for rows + inner loop for columns”. For beginners, 2D arrays are a natural extension of array knowledge. With matrix analogies and nested loop practice, you will quickly become proficient!
Practice Suggestion: Try using a 2D array to store a 3x3 matrix and traverse it with both loop methods to observe the differences.