Sub topic 2
Integer.valueOf and Wrapper Object Traps
Assume you know Java primitive types, classes, ==, equals, and basic List and Map use. This chapter focuses on Integer, but the same ideas apply to other wrapper classes.
`Integer.valueOf` and deprecated constructors
Integer.valueOf creates or returns an Integer object for an int value. Java recommends it instead of the constructors new Integer(int) and new Integer(String), which have been deprecated since Java 9.
The constructors always create a new object. valueOf can reuse an existing object, which reduces unnecessary allocation.
public class ValueOfExample {
public static void main(String[] args) {
Integer fromNumber = Integer.valueOf(42);
Integer fromText = Integer.valueOf("42");
System.out.println(fromNumber);
System.out.println(fromText);
}
}Integer.parseInt("42") returns the primitive int value 42. Integer.valueOf("42") returns an Integer object.
The wrapper cache and the `==` surprise
Integer.valueOf must cache values from -128 through 127. A cache stores objects so they can be reused. Java implementations may cache additional values.
flowchart TD
A["Integer.valueOf(127)"] --> B{"Value in cache?"}
B -->|Yes| C["Return shared Integer object"]
B -->|No| D["Create or return an Integer object"]Therefore, this result depends on caching:
Integer a = Integer.valueOf(127);
Integer b = Integer.valueOf(127);
System.out.println(a == b); // true
Integer c = Integer.valueOf(1000);
Integer d = Integer.valueOf(1000);
System.out.println(c == d); // Do not rely on this resultComparing wrappers correctly
Use equals to compare wrapper values. Use compareTo when you need ordering.
Integer first = 1000;
Integer second = 1000;
System.out.println(first.equals(second)); // true
System.out.println(first.compareTo(second) == 0); // trueequals requires a non-null receiver. For values that might be null, use Objects.equals(first, second).
Unboxing null
Unboxing converts an Integer to an int. The compiler inserts a call similar to intValue(). Calling that method on null throws NullPointerException.
import java.util.HashMap;
import java.util.Map;
public class SafeUnboxing {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>();
int score = scores.getOrDefault("Ada", 0);
System.out.println(score); // 0
}
}Use getOrDefault, a null check, or an Optional before assigning a possibly missing Integer to an int.
Exercise
Why should Integer.valueOf(1000) == Integer.valueOf(1000) not be used to compare values?
Show answer
== compares object references, and values outside the required cache range may be represented by different objects.