×

java · level 2 · unit 1 · lesson 3

  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

Lists hold objects, so numbers travel in a wrapper.

Angle brackets only take classes, and int is not a class. Put int between them and Java stops with unexpected type. Each plain type has a to use instead: for int, Double for double and Boolean for boolean.

You will hardly notice the wrapper. scores.add(7) wraps the 7 for you, and int first = scores.get(0); unwraps it again. This is called : Java pops the number in a little box and takes it out when you need it.

A for-each loop works on a list the same way it works on an array, so a running total looks the same as before.

import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> scores = new ArrayList<>();
        scores.add(7);
        scores.add(12);
        scores.add(5);
        int total = 0;
        for (int score : scores) {
            total = total + score;
        }
        System.out.println(scores + " add up to " + total);
    }
}

Integer and Double start with a capital letter, because they are classes.