java · level 1 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Which planet? Make a guess.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
public static void main(String[] args) {
String[] planets = {"Mercury", "Venus", "Earth"};
System.out.println(planets[1]);
}
}
your turn
Your turn. Swap the players.
Choose a new captain for slot 0 on line 5 and a new player for slot 2 on line 6. Then press run to see the new team.
output
press run to see what happens
fix it
Where did the lemon cake go? Fix it!
output
press run to see what happens
- Java stopped with an exception while running. Which index does line 4 ask for?
- There are 3 cakes, so the slots are 0, 1 and 2. There is no slot 3.
- Change
cakes[3]tocakes[2]on line 4, then press run.
nailed it
you can find any item by its index. :D
- The first item is at index 0.
- The last item is at
length - 1. - Change a slot with
name[index] = value;.
new words in your collection
- index
- exception
This lesson isn’t saved. A free account remembers every lesson you finish.