Wrapper Classes and Autoboxing

Integer, Double and friends wrap primitives in objects so they can go into collections. Java converts back and forth automatically, with one trap.

Java · beginner · 8 min · 12 steps · free

What you'll learn

WrapperDemo.java

import java.util.ArrayList;

public class WrapperDemo {
    public static void main(String[] args) {
        int raw = 42;
        Integer boxed = raw;               // autoboxing: int to Integer
        int back = boxed;                  // unboxing: Integer to int
        int parsed = Integer.parseInt("17");
        ArrayList<Integer> list = new ArrayList<>();
        list.add(7);                       // 7 is boxed to fit in the list
        Integer big1 = 1000;
        Integer big2 = 1000;
        boolean sameObject = big1 == big2;
        boolean sameValue = big1.equals(big2);
        System.out.println(back + parsed + " " + sameObject + " " + sameValue);
    }
}

Step by step

  1. The program starts in main. args holds its command-line arguments (none here). raw is created on the stack with the value 42.
  2. Autoboxing: Java wraps the int 42 in an Integer object.
  3. Unboxing: the int value is taken back out.
  4. Integer.parseInt turns text into an int.
  5. list is created on the stack and points to a new ArrayList on the heap: [].
  6. Collections hold objects only, so 7 is boxed automatically.
  7. big1 is created on the stack and points to a new Integer on the heap: 1000.
  8. big2 is created on the stack and points to a new Integer on the heap: 1000.
  9. == on two Integer objects compares references. Two separate 1000 objects: false.
  10. sameValue is created on the stack with the value true.
  11. It prints 59 false true.
  12. sameObject is false but sameValue is true. Use equals for wrappers; == only compares which object.

Common mistakes

Best practices

Key takeaways

Check yourself

Wrapper of char?

Answer: Character. char → Character.

Integer a = 1000, b = 1000; a == b?

Answer: Usually false. == compares references.

·

More in Arrays and Text