AI Hints
Home›Java Tutorial›ArrayList, Generics and Wrapper Classes
Java · Lesson 84 of 120

Wrapper Classes and Autoboxing

Integer, Double and friends.

⏱ 2 min read▶ Video at 1:46:41🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Collections can only hold objects, not primitives like int. So each primitive has an object twin, called a wrapper class. Int has Integer, and double has Double.

  • Collections hold objects
  • int is a primitive
  • Integer is its twin

Primitives and their wrappers

Each primitive has a wrapper class, with a capital letter. Most are just the name, capitalised. Int and char are the two special ones.

PrimitiveWrapper
intInteger
doubleDouble
booleanBoolean
charCharacter
longLong

Autoboxing

A list of numbers uses Integer, in the angle brackets. But we can add plain ints. Java wraps them automatically. That's autoboxing. Reading them back as int unwraps them automatically, too. Wrapper classes also hold useful things, like max value, and parse int. But a wrapper can be null. And unwrapping null crashes. Run it. The total is two hundred and forty seven. And then a null pointer exception.

Main.javajava
import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> scores = new ArrayList<>();
        scores.add(70);
        scores.add(85);
        scores.add(92);
        int total = 0;
        for (int s : scores) total += s;
        System.out.println("Total: " + total);
        System.out.println("Max int: " + Integer.MAX_VALUE);
        System.out.println("Parsed: " + (Integer.parseInt("15") + 1));
        Integer missing = null;
        int oops = missing;
    }
}
Output
Total: 247
Max int: 2147483647
Parsed: 16
Exception in thread "main" java.lang.NullPointerException: Cannot invoke
"java.lang.Integer.intValue()" because "missing" is null
    at Main.main(Main.java:14)

Summary

Each primitive has a wrapper class, like Integer for int. Java converts between them automatically. But a wrapper can be null. Next, a map, which links keys to values.

Key takeaways
  • List<Integer>
  • Autoboxing
  • Beware null
Next up: HashMap — keys and values