2D Array Basics & Nested Iteration
Understand 2D arrays (jagged allowed), rows vs columns, m.length and m[0].length, and nested for iteration.
What is 2D?
2D array is an array of arrays. It may be rectangular or jagged (rows can have different lengths).
Declare & Create
Declare and create:
public class Main {
public static void main(String[] args) {
// Way 1: Create a 2D array with fixed size
int[][] a = new int[2][3];
// 2 rows, 3 columns → default values = 0
// [
// [0, 0, 0],
// [0, 0, 0]
// ]
// Way 2: Create and initialize directly
int[][] b = {
{1, 2, 3},
{4, 5, 6}
};
// [
// [1, 2, 3],
// [4, 5, 6]
// ]
// Print array a
System.out.println("Array a:");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
// Print array b
System.out.println("Array b:");
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
}
}