Lesson 15 / 38

Multi-Dimensional Arrays, Arrays & Varargs

Work with 2-D and jagged arrays, unlock more of java.util.Arrays (binarySearch, deepToString, asList), and see how varargs desugar to arrays under the hood.

2-D and jagged arrays

A 2-D array is really an array of arrays, so its rows need not be the same length ("jagged"). Access with grid[row][col]; iterate with nested for-each.

int[][] grid = { {1, 2, 3}, {4, 5}, {6} };  // jagged
for (int[] row : grid) {
    for (int v : row) System.out.print(v + " ");
}
// 1 2 3 4 5 6

More of java.util.Arrays

Arrays.binarySearch needs a sorted array. Arrays.asList wraps an array as a fixed-size List (no add/remove). Arrays.deepToString prints nested arrays properly, unlike plain toString.

int[] a = {1, 3, 5, 7};
System.out.println(Arrays.binarySearch(a, 5));  // 2

int[][] grid = {{1, 2}, {3, 4}};
System.out.println(Arrays.deepToString(grid));  // [[1, 2], [3, 4]]

List<String> fixed = Arrays.asList("a", "b");
// fixed.add("c");   // UnsupportedOperationException

Varargs are just an array

int... nums is syntactic sugar: inside the method, nums is an int[]. A varargs parameter must be last, and you can pass zero args, several args, or an array directly.

static void report(String label, int... values) {
    System.out.println(label + ": " + values.length);
}

report("a");                 // a: 0
report("b", 1, 2, 3);        // b: 3
report("c", new int[]{9});   // c: 1