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.valueOfreturns an object. A parser such asInteger.parseIntreturns 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
intcannot widen then box toLongin a method call.Integer.valueOf(int)caches-128to127and may cache more. The Java SE 8 language also guarantees identity for two boxings of the sameintliteral in that range.
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.
| Primitive | Wrapper Class | Superclass | Java 8 Constructors | Parse Method -> Return Type | Documented Reuse for valueOf(primitive) |
|---|---|---|---|---|---|
boolean | Boolean | Object | boolean, String | parseBoolean(String) -> boolean | TRUE, FALSE |
byte | Byte | Number | byte, String | parseByte(String) -> byte | -128 to 127 |
short | Short | Number | short, String | parseShort(String) -> short | -128 to 127 |
char | Character | Object | char only | None (charAt on String) | '\u0000' to '\u007F' (0..127) |
int | Integer | Number | int, String | parseInt(String) -> int | -128 to 127 (min) |
long | Long | Number | long, String | parseLong(String) -> long | No particular range required |
float | Float | Number | float, double, String | parseFloat(String) -> float | No guaranteed identity |
double | Double | Number | double, String | parseDouble(String) -> double | No guaranteed identity |
Wrapper Constructor Quirks
In Java SE 8, wrapper constructors remain active and appear regularly in code-tracing questions:
Characterhas NOStringconstructor:new Character('a')compiles, whilenew Character("a")fails to compile.ByteandShorthave NOintconstructor:new Byte(10)andnew Short(10)fail compilation because10is anintliteral; you must cast (new Byte((byte) 10)) or pass aString(new Byte("10")).Floathas three constructors:new Float(3.14f),new Float(3.14)(doubleconstructor), andnew Float("3.14")all compile.Boolean(String)accepts any string ornull:new Boolean("TrUe")evaluates totrueusing case-insensitive matching against"true". Any other string—including"yes","1"," true "(leading/trailing spaces), ornull—producesfalse.
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.).Characterdoes not define aparseCharacterorparseCharmethod.
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:
- Strict fixed arity: Includes exact types and widening conversions, without boxing or unboxing.
- Loose fixed arity: Also permits boxing or unboxing and certain widening conversions after them.
- 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 (trueforc == 128), throwingNullPointerExceptionif the wrapper isnull. - Cross-type
.equals():Integer.valueOf(1).equals(Long.valueOf(1L))returnsfalsebecause.equals()requires both operands to have the exact same wrapper class.
Which expression compiles cleanly AND returns a primitive int or boolean (rather than throwing an exception or returning a wrapper object)?
Character.parseChar("A")
Integer.valueOf("42")
Boolean.parseBoolean("TrUe")
new Boolean("yes")
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);
}
}
Prints Integer true
Prints double followed by throwing a NullPointerException at runtime
Fails to compile because show(10) is ambiguous between double and Integer
Prints Long false
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));
The first two values are true and false. The third is unspecified, and the fourth is true.
The first and second values are both true. The third is unspecified, and the fourth is true.
The first value is unspecified. The second and third are false, and the fourth is true.
The four values must be true, false, true, and false.
Sections you finish are checked off in the contents.