Arrays

An array is a fixed number of slots, all holding the same type of value, sitting next to each other in memory so any one of them can be reached instantly by its position. It's the simplest way to keep a batch of related values under a single name.

Declaring and filling an array

You can create an array and fill it in one line using curly braces, or size it up front and assign values into it individually. Positions — called indexes — start counting at zero, not one.

</> TempReadings.java
public class TempReadings {
    public static void main(String[] args) {
        int[] readings = {68, 71, 74, 69, 72};

        System.out.println("First reading: " + readings[0]);
        System.out.println("Last reading: " + readings[4]);
        System.out.println("Total slots: " + readings.length);
    }
}
Output
First reading: 68
Last reading: 72
Total slots: 5

An array with five values has valid indexes 0 through 4 — asking for readings[5] doesn't quietly return something empty, it crashes the program with an ArrayIndexOutOfBoundsException. That off-by-one mistake is common enough that it's worth internalizing early: the last valid index is always length - 1.

Note also that .length here has no parentheses — it's a field on the array, not a method call like String's .length(). Java isn't consistent about this between the two, and there's no way around just remembering it.

Fixed size, one type

An array's size is locked in the moment it's created. There's no way to add a sixth reading to readings later — you'd have to build a new, larger array and copy the old values in, which is exactly what a growable structure like ArrayList (covered later in this course) does automatically for you. In exchange for that rigidity, arrays are fast and memory-efficient, which is why they're still the right tool when you know the size won't change, or when you're working with performance-sensitive code.

Looping over an array

A standard for loop works with an array whenever you need the index itself — for printing positions, or comparing neighboring elements. When you just need each value in turn and don't care about its position, the enhanced for loop (also called for-each) is shorter and harder to get wrong:

</> AverageTemp.java
public class AverageTemp {
    public static void main(String[] args) {
        int[] readings = {68, 71, 74, 69, 72};
        int sum = 0;

        for (int reading : readings) {
            sum += reading;
        }

        double average = (double) sum / readings.length;
        System.out.println("Average: " + average);
    }
}
Output
Average: 70.8

for (int reading : readings) reads as "for each reading in readings" — no index variable, no risk of an off-by-one error, no chance of accidentally reading past the end. Its one limitation is that you can't modify the array through it, and you don't get access to the current position if you need one.

Two-dimensional arrays

An array's elements can themselves be arrays, which is how Java represents a grid — a seating chart, a tic-tac-toe board, a spreadsheet of numbers. You index into it twice, once for the row and once for the column:

</> SeatingChart.java
public class SeatingChart {
    public static void main(String[] args) {
        String[][] seats = {
            {"Ava", "Ben", "Cleo"},
            {"Dan", "Eve", "Finn"}
        };

        System.out.println(seats[0][1]); // row 0, column 1
        System.out.println(seats[1][2]); // row 1, column 2
    }
}
Output
Ben
Finn
Note: arrays are reference types, not primitives — passing an array into a method hands over a reference to the same underlying data, not a copy. Changing an element inside that method changes the original array too, which is a habit worth keeping in mind once methods enter the picture.