Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 201 ยท Collections

Wrapper Classes and Autoboxing

Learn Java wrapper classes - Integer, Double, Boolean and friends, autoboxing and unboxing, valueOf vs parseInt, the Integer cache, == pitfalls and null NPEs.

Java has two kinds of values. The eight primitive types (int, double, boolean and the rest) are plain, fast values with no methods. Everything else is an object. Most of the time the line between them doesn't matter, but sometimes you need an int to behave like an object: to store it in a List, use it as a key in a Map, or represent "no value" with null.

That's what wrapper classes are for. Each primitive has a matching class that wraps one value in an object, and the compiler converts between the two automatically, a feature called autoboxing. This lesson starts the Collections chapter because every collection of numbers relies on it, and because its few sharp edges cause real bugs.

The eight wrapper classes

Primitive Wrapper Example
byte Byte Byte.valueOf((byte) 7)
short Short Short.valueOf((short) 300)
int Integer Integer.valueOf(42)
long Long Long.valueOf(42L)
float Float Float.valueOf(1.5f)
double Double Double.valueOf(1.5)
char Character Character.valueOf('x')
boolean Boolean Boolean.valueOf(true)

All of them live in java.lang (no import needed), are immutable (an Integer object holding 5 holds 5 forever) and are final. The six numeric wrappers extend the abstract class Number, which has intValue(), longValue(), doubleValue() and friends.

Generics only accept reference types, so List<int> is a compile error. You write List<Integer> instead, and the list stores Integer objects.

Autoboxing and unboxing

Boxing converts a primitive to its wrapper; unboxing converts back. Since Java 5 the compiler inserts these conversions for you wherever a value of one kind is used where the other is expected:

Java Boxing and unboxing happen automatically

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What the compiler really writes is plain method calls: Integer boxed = Integer.valueOf(42); and int plain = boxed.intValue();. Keeping that in mind explains every pitfall below. Note counter++ in particular: since Integer is immutable, the increment unboxes, adds and boxes a brand-new object.

Converting strings and numbers

Wrapper classes are also where Java keeps its conversion helpers. Two families look alike but return different things:

  • parseXxx(String) returns a primitive: Integer.parseInt("42") is an int.
  • valueOf(String) returns a wrapper: Integer.valueOf("42") is an Integer.

Use parseInt when you want a number to compute with, and valueOf when you need an object anyway. Both throw NumberFormatException for bad input (see Type Casting and Conversion).

Java Parsing, formatting and handy static methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Boolean.parseBoolean never throws: anything other than "true" (ignoring case) becomes false, including "yes" and "1". If you need strict parsing, check the text yourself.

To go the other way, String.valueOf(42), Integer.toString(42) and "" + 42 all give "42".

The Integer cache and the == trap

This is the most famous wrapper bug. == on two objects asks whether they are the same object, not whether they hold the same value. And Integer.valueOf (which autoboxing calls) reuses cached objects for small values:

Java Why == on Integer works until it doesn't

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output shows true for 127 and false for 128. The language guarantees that boxing values from -128 to 127 returns cached objects (also all Booleans, all Bytes and chars up to \u007f). Outside that range, each boxing usually creates a new object. The upper bound can even be raised with a JVM option, so code that "works" with == may break on another machine. Tests with small numbers pass, and production with real IDs fails.

The rules:

  • Compare wrapper values with equals (or Objects.equals when either side may be null).
  • When one side is a primitive, == unboxes the wrapper and compares values. That's correct but fragile; it throws if the wrapper is null.
  • equals returns false for different wrapper types, even with the same number: Long.valueOf(5).equals(5) is false, because 5 boxes to an Integer. Use 5L.
  • For ordering, use compareTo or Integer.compare(x, y), never subtraction (which can overflow).

The constructors new Integer(5) and friends are deprecated for removal. Always use valueOf or autoboxing.

null and the unboxing NullPointerException

A wrapper variable can hold null; a primitive can't. Unboxing null calls a method on nothing, so it throws a NullPointerException, often on a line that doesn't look like it dereferences anything:

Java Hidden unboxing NullPointerExceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The second case surprises even experienced developers. When one branch of ?: is an int and the other an Integer, the whole expression has type int, so the Integer branch is unboxed, and null explodes. Make both branches Integer to keep the null.

Guidelines:

  • Use primitives for local variables, counters and fields that always have a value.
  • Use wrappers only where you need an object: collection elements, generics, or a field where null deliberately means "unknown" (such as a database column that allows NULL). For optional values in method results, an OptionalInt or Optional is usually clearer than a nullable Integer.
  • With maps, prefer getOrDefault, merge or containsKey over unboxing get directly (see HashMap).

Floating-point wrappers: equals vs ==

Double.equals and == disagree in two corner cases, because equals compares the exact bit patterns:

Java
double nan = Double.NaN;
nan == nan                                          // false: NaN equals nothing
Double.valueOf(nan).equals(nan)                     // true
0.0 == -0.0                                         // true
Double.valueOf(0.0).equals(-0.0)                    // false
Double.compare(0.0, -0.0)                           // 1: -0.0 sorts first

That's what lets a HashSet<Double> find NaN again. For sorting doubles, Double.compare gives a consistent total order.

The cost of boxing

Every boxed value outside the cache is a separate object on the heap, roughly 16 bytes for an Integer compared with 4 bytes for an int, plus a reference to reach it. Accidental boxing in a hot loop creates millions of short-lived objects:

Java Accidental boxing in a loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The sums are identical; the boxed loop is usually several times slower. Exact times vary from run to run and machine to machine, and the JIT can sometimes remove the boxing, but you shouldn't count on it. For large amounts of numeric data, use arrays of primitives (int[], long[]) or primitive streams (IntStream, LongStream), which never box. A List<Integer> of a million numbers holds a million separate objects.

A list pitfall: remove(int) vs remove(Object)

List<Integer> has two remove methods, and an int argument always picks the index version:

Java
List<Integer> ids = new ArrayList<>(List.of(5, 10, 15));
ids.remove(1);                     // removes the element AT INDEX 1 -> [5, 15]
ids.remove(Integer.valueOf(15));   // removes the VALUE 15 -> [5]

The compiler chooses an overload without boxing first, so remove(1) never means "remove the value 1". You'll meet this again in ArrayList.

The same rule applies to your own methods. When several overloads could match, Java tries them in three phases: first exact matches and widening of primitives (int to long), then boxing and unboxing, and only then varargs. So a call log(5) prefers log(long) over log(Integer), and log(Integer) over log(int...). Method Overloading walks through the details. The practical lesson: avoid overloads that differ only in a primitive versus its wrapper, because readers can't predict which one runs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? Integer x = 200, y = 200; System.out.println(x == y);

    Only -128 to 127 are guaranteed to be cached. 200 is normally boxed into two separate objects, and == compares references. Use equals.
  2. 2. What is the type of Integer.parseInt("12") and of Integer.valueOf("12")?

    The parseXxx methods return primitives and the valueOf methods return wrapper objects.
  3. 3. Map<String, Integer> m = new HashMap<>(); int n = m.get("a"); What happens?

    get returns null for a missing key, and unboxing null into an int throws NullPointerException. Use getOrDefault("a", 0).
  4. 4. What does Long.valueOf(7).equals(7) return?

    Wrapper equals returns false for a different wrapper type. Long.valueOf(7).equals(7L) would be true.
  5. 5. Why does List<int> fail to compile?

    Generics work only with reference types. The wrapper Integer lets a list hold int values, with autoboxing doing the conversions.

Summary

  • Each primitive has an immutable wrapper class (Integer, Double, Boolean, Character, ...), needed for collections, generics and null.
  • Autoboxing calls valueOf and unboxing calls xxxValue(); the compiler inserts them for you.
  • parseInt and friends return primitives; valueOf returns wrappers; both throw NumberFormatException on bad input.
  • Compare wrappers with equals or Objects.equals; == compares references and only seems to work for cached values (-128 to 127).
  • Unboxing null throws NullPointerException, including inside ?: expressions with a primitive branch and comparisons with primitives.
  • Boxing costs memory and time; prefer primitives, primitive arrays and IntStream for numeric work.

Next: The Collections Framework, a map of Java's lists, sets, queues and maps and how to choose between them.