Stop 03 · Control Flow, Methods & ArraysTopics · 8/8

Arrays & 2D Arrays

Part of the Java Roadmap

In short

Thirty students' marks, seven days of temperatures, a cinema hall of seats: when you have many values of the same kind, you want them in one numbered row, not thirty separate variables.

Arrays hold a fixed number of elements of one type, indexed from 0. 2D arrays are arrays of arrays, useful for grids and matrices. Accessing an invalid index throws ArrayIndexOutOfBoundsException.

The jaadu stands in front of a small hostel building with neat rows of identical doors on three floors, holding a ring of numbered keys.

Think of it like this

Hostel rooms on a corridor

A hostel corridor has rooms numbered 0, 1, 2 and so on, all the same size, and the number of rooms is fixed when it is built. That is an array. A whole hostel with several floors, each with its own corridor, is a 2D array: you need a floor number and a room number.

Watch it happen

int[] marks = {78, 92, 65, 88, 71}

78
0
92
1
65
2
88
3
71
4

1/5Five ints in one block. Indexes go from 0 to 4, and marks.length is 5.

The big ideas

What you need to know

Fixed size

new int[5] makes exactly five slots, all starting at 0. You cannot grow an array; use ArrayList for that.

Zero-based

The first element is [0] and the last is [length - 1]. Going outside throws ArrayIndexOutOfBoundsException.

2D = array of arrays

int[][] grid = new int[3][4]; is 3 rows of 4. grid[row][col] reaches one cell.

Arrays helper class

Arrays.toString, Arrays.sort, Arrays.fill and Arrays.copyOf save you from writing loops.

See it in code

Walk through the code

java
1import java.util.Arrays;2 3public class Marks {4    public static void main(String[] args) {5        int[] marks = {78, 92, 65, 88, 71};6 7        int total = 0;8        for (int m : marks) total += m;9        double avg = (double) total / marks.length;10 11        int[] sorted = Arrays.copyOf(marks, marks.length);12        Arrays.sort(sorted);13        System.out.println(Arrays.toString(sorted)); // [65, 71, 78, 88, 92]14        System.out.println("Average: " + avg);15 16        // 3 students x 2 subjects17        int[][] scores = {18            {80, 75},19            {90, 85},20            {60, 70}21        };22        for (int s = 0; s < scores.length; s++) {23            int sum = 0;24            for (int sub = 0; sub < scores[s].length; sub++) {25                sum += scores[s][sub];26            }27            System.out.println("Student " + (s + 1) + " total: " + sum);28        }29    }30}

1/5An array literal. Java counts the elements and sets the length to 5.

Summing, averaging and sorting a 1D array, then totalling each row of a 2D array.

Save yourself the pain

Common mistakes

Oops

System.out.println(marks); and seeing [I@1b6d3586.

Do this instead

Arrays do not print their contents. Use Arrays.toString(marks), or Arrays.deepToString for 2D.

Oops

Looping with i <= marks.length.

Do this instead

The last valid index is length - 1. Use i < marks.length.

Your mission

Weekly temperatures

~20 min

Quick check

Given int[] a = new int[4];, what is a[4]?

Go deeper

  1. 1Find the sum, average and max of an int array.
  2. 2Add and multiply two matrices using 2D arrays.
  3. 3Use Arrays.toString() and Arrays.sort() from java.util.Arrays.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge