CKTIS / Java
Deprecated Integer(int) constructor
Each successful call to `Integer(int)` creates a distinct wrapper object. In new code, use `Integer.valueOf(int)` or autoboxing when you need a wrapper, not a fresh identity.
Version: Java SE 21
Syntax
@Deprecated(since="9", forRemoval=true)
public Integer(int value)With an int argument, new Integer(n) calls the java.lang.Integer(int) constructor. Every successful call creates a fresh object representing n, even if another object already represents that number. Java SE 21 still provides the constructor but marks it @Deprecated(since="9", forRemoval=true): it has been deprecated since Java 9 and is marked for removal. Unlike the Integer(String) overload, it does not parse text. That overload throws NumberFormatException if the text cannot be parsed as an int.
Keep the value as an int if you only need the number. If you need a wrapper, use Integer.valueOf(n) or autoboxing, as in Integer x = n; for an int variable n. valueOf(int) always caches values from -128 through 127 inclusive and may cache others. The autoboxing rule guarantees the same reference when the same value in that range is boxed repeatedly from an int constant expression. Neither alternative should be used to obtain a fresh identity.
With two Integer operands, == tests reference identity; equals compares the wrapped values of two Integer objects. With an Integer and an int, == unboxes the Integer and compares the numbers; unboxing null throws NullPointerException. Integer is a value-based class: do not make program logic depend on instance identity or use its instances for synchronization.
Examples
public class IntegerConstructorDemo {
public static void main(String[] args) {
Integer a = new Integer(42);
Integer b = new Integer(42);
Integer c = Integer.valueOf(42);
Integer d = Integer.valueOf(42);
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(c == d);
}
}Result
false true true
The two constructor calls for `42` produce distinct objects (`false`) with equal values (`true`). The two `Integer.valueOf(42)` calls return the same cached object (`true`). The constructor is used deliberately as a historical example; compiler removal warnings are not part of the program output.
Related lessons
- Java · Lesson 4 · Advanced · Version: 2