3.3 Wrapper Classes, Autoboxing, Unboxing & the Integer Cache

Key Takeaways

  • All eight java.lang wrapper classes are final and immutable; Byte, Short, Integer, Long, Float, and Double extend Number, while Boolean and Character extend Object directly

  • A wrapper factory such as Integer.valueOf returns an object. A parser such as Integer.parseInt returns a primitive. Verify the API’s accepted text and exception rules for each parser.

  • Unboxing a null wrapper reference in an assignment, arithmetic operation, or if condition compiles cleanly but throws NullPointerException at runtime

  • Overload resolution tries strict fixed arity, loose fixed arity, then variable arity. Thus primitive widening can win before boxing, and an int cannot widen then box to Long in a method call.

  • Integer.valueOf(int) caches -128 to 127 and may cache more. The Java SE 8 language also guarantees identity for two boxings of the same int literal in that range.

Last updated: November 2026

The Eight Wrapper Classes in java.lang

Java collections (ArrayList, HashMap) and generics (List<Integer>) cannot store primitives directly—they require object references. For every primitive type, java.lang provides a corresponding final, immutable wrapper class.

PrimitiveWrapper ClassSuperclassJava 8 ConstructorsParse Method -> Return TypeDocumented Reuse for valueOf(primitive)
booleanBooleanObjectboolean, StringparseBoolean(String) -> booleanTRUE, FALSE
byteByteNumberbyte, StringparseByte(String) -> byte-128 to 127
shortShortNumbershort, StringparseShort(String) -> short-128 to 127
charCharacterObjectchar onlyNone (charAt on String)'\u0000' to '\u007F' (0..127)
intIntegerNumberint, StringparseInt(String) -> int-128 to 127 (min)
longLongNumberlong, StringparseLong(String) -> longNo particular range required
floatFloatNumberfloat, double, StringparseFloat(String) -> floatNo guaranteed identity
doubleDoubleNumberdouble, StringparseDouble(String) -> doubleNo guaranteed identity

Wrapper Constructor Quirks

In Java SE 8, wrapper constructors remain active and appear regularly in code-tracing questions:

  • Character has NO String constructor: new Character('a') compiles, while new Character("a") fails to compile.
  • Byte and Short have NO int constructor: new Byte(10) and new Short(10) fail compilation because 10 is an int literal; you must cast (new Byte((byte) 10)) or pass a String (new Byte("10")).
  • Float has three constructors: new Float(3.14f), new Float(3.14) (double constructor), and new Float("3.14") all compile.
  • Boolean(String) accepts any string or null: new Boolean("TrUe") evaluates to true using case-insensitive matching against "true". Any other string—including "yes", "1", " true " (leading/trailing spaces), or null—produces false.

valueOf(...) vs. parseXxx(...) and NumberFormatException

Two static factory/utility families convert inputs to wrappers or primitives:

  • Wrapper.valueOf(...) returns a wrapper object (Integer, Double, Boolean, etc.) and uses the internal cache when available. For numeric wrappers, valueOf(String) parses the text and returns a wrapper representing the parsed value. The parsed value and reference identity are separate questions.
  • Wrapper.parseXxx(String) returns a primitive (int, double, boolean, etc.). Character does not define a parseCharacter or parseChar method.
int p = Integer.parseInt("42");          // returns primitive int 42
Integer w = Integer.valueOf("42");       // returns an Integer representing 42
boolean b = Boolean.parseBoolean("TRUE");// returns primitive boolean true

// Runtime exception examples:
// int bad1 = Integer.parseInt("42.0");  // throws NumberFormatException
// byte bad2 = Byte.parseByte("200");    // throws NumberFormatException (out of range)
// Integer bad3 = Integer.valueOf("1_000"); // throws NumberFormatException

An integral parser throws NumberFormatException for invalid text or a value outside its range. Floating-point parsers recognize additional inputs such as "NaN" and "Infinity", and may produce infinity or zero from a syntactically valid number with extreme magnitude. Float.parseFloat(null) and Double.parseDouble(null) throw NullPointerException.

Autoboxing, Unboxing & the NullPointerException Trap

Boxing converts a primitive value to its wrapper type. Unboxing obtains the primitive value. A Java 8 compiler commonly implements boxing using valueOf. The language defines when the conversion is allowed and what identity it guarantees:

Integer boxed = 10;          // compiler emits: Integer.valueOf(10)
int unboxed = boxed;         // compiler emits: boxed.intValue()

Integer sum = boxed + 5;     // unboxes boxed -> 10, adds 5 -> 15, boxes 15

Caution

Unboxing a null wrapper reference compiles without warning and throws NullPointerException at runtime—whether in an assignment (int x = nullInt;), arithmetic (nullInt + 1), relational check (nullInt > 0), or conditional (if (nullBool)).

Another classic List<Integer> trap involves remove:

List<Integer> nums = new ArrayList<>();
nums.add(1);
nums.add(2);
nums.remove(1);                  // Calls remove(int index): removes element at index 1 (value 2)!
nums.remove(Integer.valueOf(1)); // Calls remove(Object): removes value 1

Because List defines both remove(int index) and remove(Object o), passing literal 1 selects the exact primitive match remove(int) rather than autoboxing 1 to Integer.

Overload Resolution: Widening Beats Boxing

When multiple overloaded methods could accept a primitive argument, the Java compiler checks three applicability phases:

  1. Strict fixed arity: Includes exact types and widening conversions, without boxing or unboxing.
  2. Loose fixed arity: Also permits boxing or unboxing and certain widening conversions after them.
  3. Variable arity: Allows trailing arguments to form a varargs array. A varargs declaration can already match in a fixed-arity phase when an array is passed directly.

The compiler chooses the most specific applicable method in the first phase that finds any candidates.

Crucially, Java never performs primitive widening followed by autoboxing in a single step:

public class OverloadRules {
    static String pick(long x)    { return "long"; }
    static String pick(Integer x) { return "Integer"; }
    static String pick(int... x)  { return "varargs"; }

    static void onlyLongWrapper(Long x) {}

    public static void main(String[] args) {
        System.out.println(pick(5)); // Prints "long" (widening beats boxing)
        // onlyLongWrapper(5);       // COMPILE ERROR: int cannot widen to long AND box to Long
        onlyLongWrapper(5L);         // Compiles cleanly
    }
}

The reverse direction—unboxing followed by widening—is allowed: given Integer x = 5;, long y = x; compiles cleanly by unboxing x to int and widening int to long.

Wrapper Immutability & the Integer Cache

Every wrapper object is immutable. Writing Integer i = 10; i++; does not mutate the object holding 10; the compiler turns i++ into i = Integer.valueOf(i.intValue() + 1), leaving i referring to an Integer holding 11. Java can reuse an existing wrapper.

The Integer.valueOf(int) API guarantees reuse from -128 to 127 and permits reuse outside that range. Java SE 8 also guarantees that boxing the same int literal in that range twice produces the same reference. The boxing rule also covers boolean literals and character literals with values 0 through 127. Larger integer values have no identity guarantee. A new Integer(127) expression produces a distinct object.

Integer a = 127, b = 127;
Integer c = 128, d = 128;
Integer e = new Integer(127);

System.out.println(a == b);       // true  (both point to cached Integer 127)
System.out.println(c == d);       // depends on implementation or cache settings
System.out.println(a == e);       // false (new Integer bypasses cache)
System.out.println(a.equals(e));  // true  (same numeric value)
System.out.println(c == 128);     // true  (primitive 128 unboxes c -> 128 == 128)

Watch two additional equality rules:

  • Mixed wrapper/primitive ==: Comparing a numeric wrapper with a primitive numeric operand unboxes the wrapper and compares numeric values (true for c == 128), throwing NullPointerException if the wrapper is null.
  • Cross-type .equals(): Integer.valueOf(1).equals(Long.valueOf(1L)) returns false because .equals() requires both operands to have the exact same wrapper class.
Test Your Knowledge

Which expression compiles cleanly AND returns a primitive int or boolean (rather than throwing an exception or returning a wrapper object)?

A

Character.parseChar("A")

B

Integer.valueOf("42")

C

Boolean.parseBoolean("TrUe")

D

new Boolean("yes")

Test Your Knowledge

What is the result of compiling and running the following code?

public class TestBox {
    static void show(Long l)    { System.out.print("Long "); }
    static void show(double d)  { System.out.print("double "); }
    static void show(Integer i) { System.out.print("Integer "); }

    public static void main(String[] args) {
        show(10);
        Integer n = null;
        System.out.println(n == 10);
    }
}
A

Prints Integer true

B

Prints double followed by throwing a NullPointerException at runtime

C

Fails to compile because show(10) is ambiguous between double and Integer

D

Prints Long false

Test Your Knowledge

What can you conclude about the output from the Java SE 8 specification?

Integer a = 127;
Integer b = 127;
Integer c = new Integer(127);
Integer d = 128;
Integer e = 128;
System.out.println((a == b) + " " + (a == c) + " " + (d == e) + " " + d.equals(e));
A

The first two values are true and false. The third is unspecified, and the fourth is true.

B

The first and second values are both true. The third is unspecified, and the fourth is true.

C

The first value is unspecified. The second and third are false, and the fourth is true.

D

The four values must be true, false, true, and false.

Sections you finish are checked off in the contents.