SyntaxPilot
Courses/Java/Lesson 8
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Java · Lesson 8 of 51

2D arrays and java.util.Arrays

queued

These are the notes for Java episode 8. You will learn why one long array is the wrong tool for a report card, what a 2D array is (an array of arrays), marks[row][col], marks.length vs marks[i].length, nested loops across rows and down columns, Arrays.toString vs Arrays.deepToString, new int[3][4], jagged arrays and the crash they cause, and the java.util.Arrays toolbox: sort, binarySearch, copyOf, fill and equals. Every example below runs as-is in the SyntaxPilot compiler, with its real output from javac 21.

The problem: a report card is a table

In episode 7 one array held one subject's marks for the whole class. A real report card is a table: 3 students (Amit, Priya, Ravi) × 4 subjects (Maths, English, Science, Hindi).

Maths English Science Hindi
Amit (0) 78 92 65 88
Priya (1) 55 70 81 60
Ravi (2) 90 85 95 99

One array per student (amit[], priya[], ravi[]) brings back the episode 7 problem: one name each, and a loop can't walk through names. The obvious idea is to put all 12 marks in one long (flat) array:

public class Main {
    public static void main(String[] args) {
        int[] marks = {78, 92, 65, 88, 55, 70, 81, 60, 90, 85, 95, 99};
        // Priya = student 1, Science = subject 2
        System.out.println("Priya, Science: " + marks[1 + 2]);
    }
}
Priya, Science: 88

Wrong! Priya's Science mark is 81; 88 is Amit's Hindi. No error, no crash: a silent wrong answer.

Why it failed: a flat array has no idea where one student ends and the next begins. The correct index is student * 4 + subject = 1 * 4 + 2 = 6, and you have to do that arithmetic in your head every time. We need an array that knows about rows.

What a 2D array is

Real-life example: a cinema hall. Seat F-12 means row F, then seat 12. You never count seats from the door.

At the cinema In Java
a seat is found by row, then seat marks[1][2]: row 1, column 2
each row is a line of seats each row marks[1] is an ordinary 1D array
the hall is all the rows int[][] marks is an array of arrays

A 2D (two-dimensional) array is an array whose elements are arrays. The first index picks the row, the second picks the column.

            col 0  col 1  col 2  col 3
marks[0] →  [ 78 ][ 92 ][ 65 ][ 88 ]     Amit
marks[1] →  [ 55 ][ 70 ][ 81 ][ 60 ]     Priya    marks[1][2] = 81
marks[2] →  [ 90 ][ 85 ][ 95 ][ 99 ]     Ravi

Declaring a 2D array, rows, columns and length

public class Main {
    public static void main(String[] args) {
        int[][] marks = {
            {78, 92, 65, 88},
            {55, 70, 81, 60},
            {90, 85, 95, 99}
        };
        System.out.println("Priya, Science: " + marks[1][2]);
        System.out.println("Students: " + marks.length);
        System.out.println("Subjects: " + marks[0].length);
    }
}
Priya, Science: 81
Students: 3
Subjects: 4
  • int[][] means "array of int[]": two pairs of brackets, two indexes.
  • Each inner { ... } is one row.
  • marks.length = number of rows (the outer array holds 3 row arrays).
  • marks[0].length = number of columns in row 0 (row 0 is an array of 4).

Printing a row: Arrays.toString and the import

marks[1] is a whole array, so printing it directly shows the type code (as in episode 7):

System.out.println(marks[1]);
[I@2a139a55

Java ships with a helper class, Arrays, in the package java.util. A package is a folder of ready-made classes. Without the import:

System.out.println(Arrays.toString(marks[1]));
Main.java:8: error: cannot find symbol
        System.out.println(Arrays.toString(marks[1]));
                           ^
  symbol:   variable Arrays
  location: class Main
1 error

With import java.util.Arrays; at the top of the file:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] marks = {
            {78, 92, 65, 88},
            {55, 70, 81, 60},
            {90, 85, 95, 99}
        };
        System.out.println(Arrays.toString(marks[1]));
    }
}
[55, 70, 81, 60]

Nested loops: walking across every row

To visit every element you need a loop inside a loop, a nested loop. The outer loop picks the row; the inner loop walks across that row's columns.

for (int s = 0; s < marks.length; s++) {          // which row (student)
    for (int j = 0; j < marks[s].length; j++) {   // which column (subject) in THIS row
        ...
    }
}

The inner limit is marks[s].length, the length of the current row. This matters for jagged arrays (below).

public class Main {
    public static void main(String[] args) {
        int[][] marks = {
            {78, 92, 65, 88},
            {55, 70, 81, 60},
            {90, 85, 95, 99}
        };
        for (int s = 0; s < marks.length; s++) {
            int total = 0;
            for (int j = 0; j < marks[s].length; j++) {
                System.out.print(marks[s][j] + " ");
                total += marks[s][j];
            }
            System.out.println("| Total: " + total);
        }
    }
}
78 92 65 88 | Total: 323
55 70 81 60 | Total: 266
90 85 95 99 | Total: 369

The same loops work for 60 students and 8 subjects: nothing is hard-coded.

Printing the whole table: toString vs deepToString

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] marks = {
            {78, 92, 65, 88},
            {55, 70, 81, 60},
            {90, 85, 95, 99}
        };
        System.out.println(Arrays.toString(marks));
        System.out.println(Arrays.deepToString(marks));
    }
}
[[I@2a139a55, [I@15db9742, [I@6d06d69c]
[[78, 92, 65, 88], [55, 70, 81, 60], [90, 85, 95, 99]]

toString goes one level deep: the outer array's elements are three row arrays, and they print as codes. deepToString goes into every level. Rule: toString for 1D, deepToString for 2D (or more).

Walking down a column: subject averages

The principal wants the class average per subject: that's a column, going down. Flip the loops: the outer loop picks a column j, the inner loop goes down every row s.

public class Main {
    public static void main(String[] args) {
        int[][] marks = {
            {78, 92, 65, 88},
            {55, 70, 81, 60},
            {90, 85, 95, 99}
        };
        String[] subjects = {"Maths", "English", "Science", "Hindi"};
        for (int j = 0; j < marks[0].length; j++) {
            int sum = 0;
            for (int s = 0; s < marks.length; s++) {
                sum += marks[s][j];
            }
            System.out.println(subjects[j] + ": " + (double) sum / marks.length);
        }
    }
}
Maths: 74.33333333333333
English: 82.33333333333333
Science: 80.33333333333333
Hindi: 82.33333333333333

(This assumes every row has the same number of columns, which is true for a rectangular table.)

new int[rows][cols] and default values

Like new int[n] in episode 7, you can create an empty table and fill it later. Every slot starts at the default value (0 for int).

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] grid = new int[3][4];
        grid[2][3] = 7;
        System.out.println(Arrays.deepToString(grid));
    }
}
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 7]]

Jagged arrays

Real-life example: a building where the ground floor has 2 flats, the first floor 4, the top floor 3. A 2D array whose rows have different lengths is a jagged array. Give only the number of rows, then create each row separately:

public class Main {
    public static void main(String[] args) {
        int[][] flats = new int[3][];
        flats[0] = new int[2];
        flats[1] = new int[4];
        flats[2] = new int[3];
        for (int f = 0; f < flats.length; f++) {
            System.out.println("Floor " + f + ": " + flats[f].length + " flats");
        }
    }
}
Floor 0: 2 flats
Floor 1: 4 flats
Floor 2: 3 flats

You can also write a jagged array directly: int[][] runs = {{4, 6}, {1, 0, 2, 4}, {6, 6, 1}};

The jagged array crash

Runs in three overs of gully cricket, with a different number of balls recorded per over. The inner loop wrongly uses row 1's length (4) for every row:

public class Main {
    public static void main(String[] args) {
        int[][] runs = {
            {4, 6},
            {1, 0, 2, 4},
            {6, 6, 1}
        };
        for (int i = 0; i < runs.length; i++) {
            for (int j = 0; j < runs[1].length; j++) {
                System.out.print(runs[i][j] + " ");
            }
            System.out.println();
        }
    }
}
4 6 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
    at Main.main(Main.java:10)

Row 0 has only 2 elements, so runs[0][2] doesn't exist. Fix: the inner limit is the current row's own length, runs[i].length:

4 6 
1 0 2 4 
6 6 1 

The java.util.Arrays toolbox

Method What it does Example result
Arrays.toString(a) a 1D array as text [65, 71, 78]
Arrays.deepToString(a) a 2D array as text [[1, 2], [3, 4]]
Arrays.sort(a) sorts smallest → largest, changes a itself
Arrays.binarySearch(a, key) index of key in a sorted array (negative if not found) 3
Arrays.copyOf(a, newLength) a real copy; extra slots get defaults; shorter length cuts [.., 0, 0]
Arrays.fill(a, value) sets every slot to value [5, 5, 5, 5]
Arrays.equals(a, b) same length and same values in the same order? true

These are static methods: you call them on the class name, Arrays.sort(...), not on an array. A method is a named piece of work you call with a dot and brackets (we'll write our own in episode 11).

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] marks = {78, 92, 65, 88, 71};
        Arrays.sort(marks);
        System.out.println(Arrays.toString(marks));
        System.out.println("88 is at index " + Arrays.binarySearch(marks, 88));
        int[] bigger = Arrays.copyOf(marks, 7);
        System.out.println(Arrays.toString(bigger));
    }
}
[65, 71, 78, 88, 92]
88 is at index 3
[65, 71, 78, 88, 92, 0, 0]

copyOf is how you "grow" an array: the length of an array can't change, but you can copy it into a bigger one.

== vs Arrays.equals

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        int[] b = {1, 2, 3};
        System.out.println(a == b);
        System.out.println(Arrays.equals(a, b));
        int[] bonus = new int[4];
        Arrays.fill(bonus, 5);
        System.out.println(Arrays.toString(bonus));
    }
}
false
true
[5, 5, 5, 5]

== asks "are these the same array (same train)?" They are two different arrays that look alike, so false. Arrays.equals compares the values slot by slot. (For 2D arrays use Arrays.deepEquals.)

Common mistakes (and the real error messages)

Mistake Real message Why Fix
marks[1 + 2] on a flat report-card array no error, wrong value (88) a flat array has no rows int[][] marks, marks[1][2]
Arrays.toString(row) without the import cannot find symbol symbol: variable Arrays Arrays lives in java.util import java.util.Arrays;
Arrays.toString(grid) on a 2D array [[I@2a139a55, [I@15db9742, [I@6d06d69c] goes one level deep Arrays.deepToString(grid)
j < runs[1].length on a jagged array ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 rows have different lengths j < runs[i].length
int[][] g = new int[][4]; ']' expected the row count is required new int[3][4] or new int[3][]
a == b to compare arrays no error, false compares references Arrays.equals(a, b)
binarySearch on an unsorted array no error, unreliable result it needs sorted input Arrays.sort(a) first

Mini project: class report card

public class Main {
    public static void main(String[] args) {
        String[] names = {"Amit", "Priya", "Ravi"};
        int[][] marks = {
            {78, 92, 65, 88},
            {55, 70, 81, 60},
            {90, 85, 95, 99}
        };
        int best = 0, bestTotal = 0;
        for (int s = 0; s < marks.length; s++) {
            int total = 0;
            for (int m : marks[s]) {
                total += m;
            }
            double percent = total * 100.0 / (marks[s].length * 100);
            System.out.println(names[s] + ": " + total + " (" + percent + "%)");
            if (total > bestTotal) {
                bestTotal = total;
                best = s;
            }
        }
        System.out.println("Class topper: " + names[best]);
    }
}
Amit: 323 (80.75%)
Priya: 266 (66.5%)
Ravi: 369 (92.25%)
Class topper: Ravi

Row s of marks belongs to names[s]: two arrays kept in step by the same index. A for-each loop works on a row because a row is an ordinary array. Extend it: print each subject's topper (walk down each column and remember the row of the maximum).

Practice

  1. Fill a 3×3 array with a multiplication table (t[i][j] = (i + 1) * (j + 1)) and print it with deepToString.
  2. Find the highest mark in each subject (column) of the report card.
  3. Add up the main diagonal of a 3×3 grid (g[0][0] + g[1][1] + g[2][2]).
  4. Sort a copy of an array and show the original is unchanged.
  5. Count how many marks in the whole 2D array are 90 or above.
Solutions and hints
  1. java int[][] t = new int[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { t[i][j] = (i + 1) * (j + 1); } } System.out.println(Arrays.deepToString(t)); // [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
  2. java for (int j = 0; j < marks[0].length; j++) { int max = marks[0][j]; for (int s = 1; s < marks.length; s++) { if (marks[s][j] > max) { max = marks[s][j]; } } System.out.println("Subject " + j + ": " + max); // 90, 92, 95, 99 }
  3. int d = 0; for (int i = 0; i < g.length; i++) { d += g[i][i]; }
  4. int[] c = Arrays.copyOf(a, a.length); Arrays.sort(c); then print both with Arrays.toString.
  5. int c = 0; for (int[] row : marks) { for (int m : row) { if (m >= 90) { c++; } } } → 4 for the report card above (92, 90, 95 and 99).

Quick quiz

What does this print?

int[][] a = {{1, 2}, {3, 4, 5}};
System.out.println(a.length + a[1].length);
  • A. 4
  • B. 5
  • C. 7
  • D. ArrayIndexOutOfBoundsException
Answer

B. 5. a.length counts the rows: 2. a[1] is the row {3, 4, 5}, so a[1].length is 3. 2 + 3 = 5.

Interview questions

  1. Does Java have true multi-dimensional arrays? No: a 2D array is an array of arrays, which is why rows can have different lengths.
  2. What is a jagged array? A 2D array whose rows have different lengths, created with new int[n][] and each row separately.
  3. What do a.length and a[0].length return for new int[3][5]? 3 and 5.
  4. Difference between Arrays.toString and Arrays.deepToString? toString prints one level; deepToString prints nested arrays too.
  5. Why can a == b be false when both arrays hold the same values? == compares references; use Arrays.equals (or Arrays.deepEquals for 2D).
  6. What must be true before Arrays.binarySearch? The array must be sorted.
  7. How do you "resize" an array? You can't; create a bigger one, e.g. Arrays.copyOf(a, newLength).

Glossary

Term Meaning Example
2D (two-dimensional) array an array whose elements are arrays: a table of rows and columns int[][] marks
row one inner array of a 2D array marks[1]
column the same position across every row marks[s][2] for every s
a.length (2D) the number of rows 3
a[i].length the number of columns in row i 4
flat array one 1D array holding a table's values in a single line {78, 92, ..., 99}
nested loop a loop inside another loop outer rows, inner columns
jagged array a 2D array whose rows have different lengths new int[3][]
package a named folder of ready-made classes java.util
import tells Java which class from a package you mean import java.util.Arrays;
java.util.Arrays Java's helper class of array methods Arrays.sort(a)
method a named piece of work you call with a dot and brackets Arrays.fill(a, 5)
static method a method called on the class name, not on an object Arrays.toString(a)
Arrays.deepToString prints nested arrays as text [[1, 2], [3, 4]]
binary search a fast search that needs a sorted array Arrays.binarySearch(a, 88)
reference a variable's link to an array in memory; == compares these a == b

Summary

  • A 2D array is an array of arrays: int[][], a[row][col].
  • a.length is the number of rows; a[i].length is row i's number of columns.
  • Nested loops walk the table: outer = rows, inner = columns; flip them to walk down a column.
  • Print with Arrays.deepToString; Arrays.toString is only for 1D arrays.
  • Jagged arrays have rows of different lengths: always use a[i].length in the inner loop.
  • java.util.Arrays (import it!) gives sort, binarySearch, copyOf, fill, equals.

Next episode: Strings: why a String never changes (immutability), the string pool, equals vs ==, and the String methods you'll use every day.