×

java · level 1 · unit 6 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Every item in an array has an , starting at 0.

Each item has an index: its position number. Java starts counting at 0, so the first item is planets[0] and the second is planets[1]. Square brackets after the name pick one out.

So the last item is always at length - 1. To change an item, put a new value in its slot: planets[1] = "Mars";. An array's size is fixed, so you cannot add slots.

Ask for a slot that is not there and Java stops with an , an error that happens while the program runs. This one is called ArrayIndexOutOfBoundsException.

import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        String[] planets = {"Mercury", "Venus", "Earth"};
        System.out.println(planets[0]);
        System.out.println(planets[planets.length - 1]);
        planets[1] = "Mars";
        System.out.println(Arrays.toString(planets));
    }
}

The index counts steps from the start, so the first item is 0 steps in.