Sub topic 5
Integer.valueOf and why the constructors are deprecated
This chapter assumes you know Java's primitive types, how to read basic class syntax, and the difference between == and equals on objects. It also assumes you have seen autoboxing, where the compiler converts between int and Integer for you. Here you will see which method the compiler calls for that conversion, why you should call it yourself instead of using new Integer(...), and what the deprecation warnings mean.
Two ways to get an Integer
Every wrapper class gives you two ways to create an object from a primitive value.
Integer viaFactory = Integer.valueOf(100); // static factory method
Integer viaConstructor = new Integer(100); // constructor, deprecatedA factory method is a static method that returns an instance. It is not required to create a new object each time. A constructor is required to create a new object every time you call it.
That difference is why valueOf is the recommended API. Integer.valueOf(int) may return an object that already exists. new Integer(int) always allocates a fresh one.
What the constructors do and their deprecation history
The wrapper constructors are deprecated in stages:
- Since Java 9, the constructors of
Integer,Long,Short,Byte,Character,Boolean,FloatandDoublecarry@Deprecated. Each one points you tovalueOf. - Since Java 16, they are marked
@Deprecated(forRemoval = true). The compiler now reports a[removal]warning instead of a plain deprecation warning. Warnings of that kind mean the API is planned for deletion from a future release.
This applies to every constructor on these classes. That includes the String forms such as new Integer("12") and new Double("1.5"), and the new Double(float) form.
The replacements are direct:
| Deprecated call | Replacement | Notes |
|---|---|---|
| `new Integer(5)` | `Integer.valueOf(5)` | May return a cached object |
| `new Integer("12")` | `Integer.valueOf("12")` | Use `Integer.parseInt("12")` if you want an `int` |
| `new Double(1.5)` | `Double.valueOf(1.5)` | No caching, but the API is the supported one |
| `new Boolean(true)` | `Boolean.valueOf(true)` or `Boolean.TRUE` | Always returns one of two shared objects |
| `new Character('a')` | `Character.valueOf('a')` | Caches `'\u0000'` to `'\u007f'` |
Why the constructors were deprecated
Three reasons drive the change.
- Wasted allocation. A constructor allocates a new object even when an equal one already exists. Small values are used constantly, so avoiding duplicates saves memory and garbage collection work.
- Identity surprises. Code that mixes
new Integer(...)with autoboxed values has objects that are equal in value but different in identity. A==comparison on such code can give a different answer depending on how each object was created. - Wrapper identity is meant to stop mattering. The JDK documents
Integerand the other wrappers as value-based classes. For such a class, two instances that are equal byequalsshould be treated as interchangeable, and you should not depend on their identity. Constructors that hand out guaranteed-unique objects encourage identity-dependent code. Removing them lets the platform change how these objects are represented later without breaking correct programs.
The value-based status has a visible effect today. If you synchronize on a wrapper, javac -Xlint:synchronization warns you:
public class SyncOnWrapper {
public static void main(String[] args) {
Integer lock = Integer.valueOf(1);
synchronized (lock) { // warning: attempt to synchronize on an instance of a value-based class
System.out.println("locked");
}
}
}Another thread could receive the very same cached Integer from valueOf(1), so unrelated code could contend for your lock. Use a dedicated private final Object lock = new Object(); instead.
Seeing the difference
The following program compares objects from valueOf with objects from the constructor. It compiles on current JDKs, and @SuppressWarnings("removal") silences the removal warning for the deliberate use of the constructor. Because the constructor is slated for removal, it may stop compiling on a future JDK.
public class ValueOfIdentity {
@SuppressWarnings("removal")
public static void main(String[] args) {
Integer a = Integer.valueOf(100);
Integer b = Integer.valueOf(100);
Integer c = new Integer(100);
Integer d = new Integer(100);
System.out.println(a == b); // true: both come from the cache
System.out.println(c == d); // false: two separate allocations
System.out.println(a == c); // false: cached object versus new object
System.out.println(a.equals(c)); // true: equal values
}
}The last line shows that the values are the same. Only identity differs, and identity is what == tests. Chapter material on the wrapper cache and on comparing wrappers covers the consequences in detail. Here the point is the origin of the difference: valueOf can share objects and the constructor cannot.
How valueOf(int) decides
For Integer, the logic is simple. If the argument is inside the cached range, valueOf returns the pre-built object for that number. Otherwise it creates a new Integer.
The specification guarantees only part of this. The Javadoc says valueOf(int) always caches values from -128 to 127 inclusive and may cache other values. The lower bound is fixed. The upper bound defaults to 127 and the HotSpot JVM lets you raise it with the -XX:AutoBoxCacheMax=<size> option. A larger cache changes which values compare equal under ==. That is another reason never to rely on == for wrappers.
Which wrappers cache
Not every valueOf caches. The rules differ by type.
| Class | Cached by valueOf | Notes |
|---|---|---|
| `Integer` | -128 to 127 (upper bound adjustable) | Guaranteed range |
| `Long` | -128 to 127 | Guaranteed range |
| `Short` | -128 to 127 | Guaranteed range |
| `Byte` | all 256 values | Every possible byte |
| `Character` | 0 to 127 | `'\u0000'` to `'\u007f'` |
| `Boolean` | both values | Returns `Boolean.TRUE` or `Boolean.FALSE` |
| `Float` | none | Always a new object in practice |
| `Double` | none | Always a new object in practice |
Because there are infinitely many useful double values and no useful small range, Float.valueOf and Double.valueOf do not cache. Two calls to Double.valueOf(1.0) normally return different objects. The specification does not promise this either way, so treat == on Double as meaningless.
public class CacheByType {
public static void main(String[] args) {
System.out.println(Long.valueOf(50) == Long.valueOf(50)); // true
System.out.println(Long.valueOf(500) == Long.valueOf(500)); // false in practice
System.out.println(Byte.valueOf((byte) 9) == Byte.valueOf((byte) 9)); // true
System.out.println(Character.valueOf('a') == Character.valueOf('a')); // true
System.out.println(Boolean.valueOf("true") == Boolean.TRUE); // true
System.out.println(Double.valueOf(1.0) == Double.valueOf(1.0)); // false in practice
}
}Lines marked "in practice" are observations of the common JDK implementation, not guarantees.
Autoboxing already calls valueOf
When you write Integer x = 42;, the compiler emits a call to Integer.valueOf(42). It never emits new Integer(42). So autoboxing inherits the cache behavior, and you get shared objects for small values without writing anything.
You can confirm this with the disassembler. Compile BoxingBasics and run javap:
javac BoxingBasics.java
javap -c BoxingBasics | grep valueOfThe output contains lines like invokestatic #7 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;. If you see invokespecial ... Integer."<init>", someone called the constructor explicitly.
Overloads of valueOf
valueOf is overloaded, and the overloads behave differently.
Integer.valueOf(int)boxes a primitive and uses the cache.Integer.valueOf(String)parses the text in base 10 and then boxes the result withvalueOf(int), so the cache applies here too.Integer.valueOf(String, int radix)parses in the given base, for example 16 for hexadecimal.
Parsing follows parseInt rules, so invalid text throws NumberFormatException. Whitespace is not trimmed, and a leading + or - is allowed.
public class ValueOfParsing {
public static void main(String[] args) {
System.out.println(Integer.valueOf("42")); // 42
System.out.println(Integer.valueOf("+42")); // 42
System.out.println(Integer.valueOf("ff", 16)); // 255
System.out.println(Integer.valueOf("42") == Integer.valueOf(42)); // true: both cached
try {
Integer.valueOf(" 42"); // leading space
} catch (NumberFormatException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}Edge cases that trip people up
A char passed to Integer.valueOf is widened
Integer.valueOf('A') compiles. The char widens to int, so you get the number 65, not a parsed digit. To get the digit value of a character, use Character.getNumericValue or Character.digit.
Short and Byte do not accept int literals
Short.valueOf(5) does not compile. The literal 5 is an int, and method invocation does not narrow int to short automatically. Write Short.valueOf((short) 5). The same applies to Byte.valueOf((byte) 5). Assignment contexts such as Short s = 5; are different: the compiler allows that constant narrowing and then boxes.
Passing null as a String
Integer.valueOf((String) null) throws NumberFormatException, not NullPointerException. This surprises people who expect a null check to come first. Boolean.valueOf((String) null) returns Boolean.FALSE without an exception, because it only tests whether the text equals "true", ignoring case.
Prefer parseInt when you need a primitive
If you want an int, calling Integer.valueOf(text) and then unboxing does extra work and, outside the cache range, allocates an object you immediately discard. Use Integer.parseInt(text) when the result goes into a primitive variable.
public class ParseVersusValueOf {
public static void main(String[] args) {
String text = "2048";
int count = Integer.parseInt(text); // no wrapper object involved
Integer boxed = Integer.valueOf(text); // wrapper, needed e.g. for a List<Integer>
System.out.println(count + boxed);
}
}Migrating old code
When a build flags constructor usage, the migration is mechanical.
- Search for
new Integer(,new Long(,new Double(,new Boolean(and the other wrapper constructors. - Replace each with the matching
valueOfcall, or withparseXxxwhere the surrounding code wants a primitive. - Check every
==or!=between wrapper objects near the changed code. A comparison that used to be always false, because both sides werenewobjects, may now be true for small values. Replace such comparisons withequalsorcompareTo. - Remove any
synchronizedblocks that lock on a wrapper object.
Step 3 matters most. Switching from the constructor to valueOf can change the result of an == test that was already a bug, so it can expose latent defects. Treat that as a benefit.
Summary of rules
- Never call a wrapper constructor in new code. It is deprecated for removal and bypasses sharing.
- Use
valueOfwhen you need a wrapper object, andparseXxxwhen you need a primitive. - Rely on autoboxing to call
valueOffor you in everyday code. - Do not depend on whether
valueOfreturns a shared object. Compare withequals. - Do not synchronize on wrapper objects.
Exercise
A teammate replaces Integer a = new Integer(500); Integer b = new Integer(500); with Integer a = Integer.valueOf(500); Integer b = Integer.valueOf(500); and leaves the line if (a == b) unchanged. Does the outcome of the comparison stay the same, and what should the line become?
Show answer
With the constructors, a == b is always false because two separate objects were created. With valueOf, 500 is outside the guaranteed cache range of -128 to 127, so the result is normally still false, but the cache upper bound can be raised with -XX:AutoBoxCacheMax, so the outcome is not guaranteed. The comparison compares identity, not value. Change it to a.equals(b) (or a.compareTo(b) == 0).
Exercise
Which of these lines fail to compile or throw at run time, and why? (1) Short.valueOf(7) (2) Integer.valueOf(" 7") (3) Integer.valueOf('7')
Show answer
(1) It fails to compile: the literal 7 is an int, and method invocation does not narrow it to short. Write Short.valueOf((short) 7). (2) It throws NumberFormatException at run time, because the parser does not trim the leading space. (3) It compiles and returns 55, the numeric code of the character '7', because the char widens to int. It is not parsed as a digit.