Wrapper classes and autoboxing
Every primitive has a class next to it: Integer for int, Double for double, Character for char and so on. The classes are needed because the collections and generics hold objects, not primitives, and because a class can have methods: parsing, formatting, comparing and the range constants.
A class for every primitive
The compiler converts between a primitive and its wrapper without a call: Integer boxed = 42; is autoboxing and int value = boxed; is unboxing. The conversion is convenient and not free: an object is allocated, or a cached one is reused, and a null wrapper cannot be unboxed at all.
The file Wrappers.java:
public class Wrappers {
public static void main(String[] args) {
int parsed = Integer.parseInt("42");
Integer boxed = Integer.valueOf(parsed);
int unboxed = boxed;
System.out.println("parsed: " + parsed);
System.out.println("boxed: " + boxed);
System.out.println("unboxed: " + unboxed);
System.out.println("max: " + Integer.MAX_VALUE);
System.out.println("binary: " + Integer.toBinaryString(10));
System.out.println("hex: " + Integer.toString(255, 16));
}
}
javac -Xlint:all Wrappers.java
java Wrappers
parsed: 42
boxed: 42
unboxed: 42
max: 2147483647
binary: 1010
hex: ff
MAX_VALUE is a constant of the class, and the two conversions toBinaryString and toString(255, 16) write the same number in another base. The wrappers are also where the size constants live, which is how lesson 008 printed the ranges without a table.
parseInt and valueOf
Integer.parseInt reads a string and returns an int; it throws NumberFormatException when the text is not a number in that base. Integer.valueOf returns an Integer, and it is the method to prefer over new Integer, which is deprecated and removed from the next release.
Both take an optional radix: Integer.parseInt("ff", 16) is 255. A program that parses user input wraps the call in a try or checks the text with a regex first, because the exception is the only signal the method gives.
The Integer cache
valueOf and autoboxing reuse objects for the values from -128 to 127. That is an implementation detail of the JDK, and it is why two boxed 127 values are the same object while two boxed 128 values are not.
public class Cache {
public static void main(String[] args) {
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println("127 == 127: " + (a == b));
System.out.println("128 == 128: " + (c == d));
System.out.println("equals: " + c.equals(d));
}
}
javac -Xlint:all Cache.java
java Cache
127 == 127: true
128 == 128: false
equals: true
The lesson is the same as with strings: == compares references, and equals compares values. A program that compares wrappers with == works for small values in a test and fails for a larger one in production, which is the worst way to learn it.
Unboxing a null
A wrapper variable may be null, because it is a reference. Unboxing it calls intValue on that reference, and the call on null throws NullPointerException. The message of the JVM names the call it could not make.
public class Unbox {
public static void main(String[] args) {
Integer boxed = null;
try {
int value = boxed;
System.out.println(value);
} catch (NullPointerException error) {
System.out.println("caught: " + error.getMessage());
}
}
}
javac -Xlint:all Unbox.java
java Unbox
caught: Cannot invoke "java.lang.Integer.intValue()" because "<local1>" is null
The message is the helpful form of the null-pointer report that Java 14 introduced: it says which method was invoked and which local variable was null. A program that must accept a missing number uses Integer and checks for null before it computes, or uses OptionalInt instead.
Exercises
- Parse "ff" in base 16 and "1010" in base 2, and print both as decimal.
- Compare Integer.valueOf(1000) with Integer.valueOf(1000) using == and equals.
- Wrap a Integer.parseInt of "12a" in a try and print the exception class.
- Put five ints into an ArrayList<Integer> and sum them, watching the autoboxing in each add.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why do the wrapper classes exist?
Answer
Collections and generics hold objects, and a class can have methods
A List<int> is illegal, so an int in a collection is an Integer, and the class supplies parse, format and range methods.
-
What does
Integer.parseInt("42")return?Answer
An int with the value 42
parseInt returns the primitive int; valueOf returns the Integer object.
-
What happens when a null Integer is unboxed?
Answer
NullPointerException
Unboxing calls intValue on the reference, and a call on null throws NullPointerException.
-
What does this program print?
public class Q1 { public static void main(String[] args) { Integer a = 100; Integer b = 100; System.out.println(a == b); } }Answer
true
Both values are in the cache, so autoboxing gives the same object twice.
-
What does this program print?
public class Q2 { public static void main(String[] args) { Integer a = 1000; Integer b = 1000; System.out.println(a == b); } }Answer
false
1000 is outside the cache, so the two boxes are different objects.
-
What does this program print?
public class Q3 { public static void main(String[] args) { System.out.println(Integer.parseInt("7") + Integer.parseInt("8")); } }Answer
15
Both calls return ints, so the addition is 7 + 8.
-
What does this program print?
public class Q4 { public static void main(String[] args) { Integer boxed = null; int value = 0; try { value = boxed; } catch (NullPointerException error) { System.out.println("null"); } System.out.println(value); } }Answer
null / 0
The unboxing throws before the assignment, so value keeps 0 and both lines print.
-
What does
Integer.toBinaryString(5)return?Answer
101
The method writes the value in base 2, without a prefix.
-
What is the safe way to compare two Integer objects by value?
Answer
equals
equals compares the values; == compares the references and depends on the cache.
-
What does a program that parses
"12a"with parseInt get?Answer
A NumberFormatException
The whole text must be a number in the given base, and the trailing a makes it invalid.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev