You skipped the intended solution:

Integer p = Integer.valueOf(1);

This pattern is known as Factory method pattern. One may ask what the benefit of this method is. Luckily, the implementation of class Integer is open-source, so let's take a look:

    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

There seems to be some kind of Integer-value cache. If one requests an Integer with a value within the cache-range, Java does not create a new object, but returns a previously created one. This works because Integers are immutable. One can even control the upper cache limit with the system property java.lang.Integer.IntegerCache.high=....

And why do the other two methods of creating an Integer generate a warning? Because they were set deprecated with Java 9.

Integer#Integer(int value):

Deprecated. It is rarely appropriate to use this constructor. The static factory valueOf(int) is generally a better choice, as it is likely to yield significantly better space and time performance. [...]

Integer#Integer(String s):

Deprecated. It is rarely appropriate to use this constructor. Use parseInt(String) to convert a string to a int primitive, or use valueOf(String) to convert a string to an Integer object. [...]

And just for completeness, here is the part for Integer.valueOf(int i):

Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.


EDIT 1: Thanks to @VGR mentioning that

Integer p = 1;

is equivilant to

Integer p = Integer.valueOf(1);

This, however, is only true for int-values between -128 and 127. The behaviour is defined in JLS §5.1.7:

[...] If the value p being boxed is the result of evaluating a constant expression (§15.28) of type boolean, char, short, int, or long, and the result is true, false, a character in the range '\u0000' to '\u007f' inclusive, or an integer in the range -128 to 127 inclusive, then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.


EDIT 2: Thanks to @DorianGray, who brought the following to my attention.

While not in the JLS, the version of javac I am using (9.0.4) does compile the boxing down to Integer.valueOf(...); as it is shown in this answer by Adam Rosenfield.

Answer from Turing85 on Stack Overflow
Top answer
1 of 2
19

You skipped the intended solution:

Integer p = Integer.valueOf(1);

This pattern is known as Factory method pattern. One may ask what the benefit of this method is. Luckily, the implementation of class Integer is open-source, so let's take a look:

    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

There seems to be some kind of Integer-value cache. If one requests an Integer with a value within the cache-range, Java does not create a new object, but returns a previously created one. This works because Integers are immutable. One can even control the upper cache limit with the system property java.lang.Integer.IntegerCache.high=....

And why do the other two methods of creating an Integer generate a warning? Because they were set deprecated with Java 9.

Integer#Integer(int value):

Deprecated. It is rarely appropriate to use this constructor. The static factory valueOf(int) is generally a better choice, as it is likely to yield significantly better space and time performance. [...]

Integer#Integer(String s):

Deprecated. It is rarely appropriate to use this constructor. Use parseInt(String) to convert a string to a int primitive, or use valueOf(String) to convert a string to an Integer object. [...]

And just for completeness, here is the part for Integer.valueOf(int i):

Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.


EDIT 1: Thanks to @VGR mentioning that

Integer p = 1;

is equivilant to

Integer p = Integer.valueOf(1);

This, however, is only true for int-values between -128 and 127. The behaviour is defined in JLS §5.1.7:

[...] If the value p being boxed is the result of evaluating a constant expression (§15.28) of type boolean, char, short, int, or long, and the result is true, false, a character in the range '\u0000' to '\u007f' inclusive, or an integer in the range -128 to 127 inclusive, then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.


EDIT 2: Thanks to @DorianGray, who brought the following to my attention.

While not in the JLS, the version of javac I am using (9.0.4) does compile the boxing down to Integer.valueOf(...); as it is shown in this answer by Adam Rosenfield.

2 of 2
3

Method 4, Integer p = Integer.valueOf(1); is the recommended way. The JavaDoc says:

Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

🌐
TutorialsPoint
tutorialspoint.com › article › create-an-integer-object-in-java
Create an Integer object in Java
December 18, 2024 - The following example creates an Integer object using the Integer constructor. This means we will create an instance of the Integer wrapper class by passing a primitive int value as 99 as an argument ?
🌐
Java Tutorial HQ
javatutorialhq.com › java tutorial › java.lang › integer
Java Integer Class Tutorial and Example
September 30, 2019 - There are two ways to instantiate the Integer object. One is two use the new keyword. Below is a sample way on how to do this: ... And the second method to create an Integer object is to use the autoboxing feature of java which directly converts a primitive data type to its corresponding wrapper ...
🌐
Medium
medium.com › javarevisited › an-interesting-interview-question-whats-the-difference-among-new-integer-127-integer-valueof-b9e4d936765d
An Interesting Interview Question: What’s the Difference Among new Integer(“127”), Integer.valueOf(“
January 10, 2025 - Actually, this question involves a subtlety in the creation and caching mechanism of the Integer object in Java. It’s a seemingly basic problem but is easy to overlook. First of all, let’s take a look at a piece of code and then conduct a specific analysis. Integer a = new Integer("127"); Integer b = new Integer("127"); System.out.println(a == b); // false Integer c = Integer.valueOf("127"); Integer d = Integer.valueOf("127"); System.out.println(c == d); // true Integer e = Integer.valueOf("128"); Integer f = Integer.valueOf("128"); System.out.println(e == f); // false
🌐
MIT
web.mit.edu › java_v1.0.2 › www › javadoc › java.lang.Integer.html
Class java.lang.Integer
Constructs an Integer object initialized to the value specified by the String parameter. The radix is assumed to be 10. ... If the String does not contain a parsable integer. ... Returns a new String object representing the specified integer in the specified radix.
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › lang › Integer.html
Integer (Java SE 17 & JDK 17)
April 21, 2026 - Constructs a newly allocated Integer object that represents the specified int value.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-lang-integer-class-java
Java.lang.Integer class in Java - GeeksforGeeks
June 21, 2022 - The variable will be pointing to the Integer object & not the Integer constant. ... 250 is created inside and outside the space of constants. Variable 'a' will be pointing the value that is outside the space of constants. Refer Fig. 4. ... After autoboxing, 'a' will be pointing to 350. Refer Fig. 5. ... If we assign a = 250 next time, it will not point to the object already present with same value, it will create a new object.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Integer.html
Integer (Java Platform SE 8 )
April 21, 2026 - Constructs a newly allocated Integer object that represents the specified int value.
Find elsewhere
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › lang › Integer.html
Integer (Java Platform SE 7 )
Constructs a newly allocated Integer object that represents the int value indicated by the String parameter.
🌐
Coderanch
coderanch.com › t › 553075 › java › invoke-Integer-object-reflection
How to invoke a new Integer object using reflection? (Java in General forum at Coderanch)
For example Let's say Class[] param = new Class[1]; param[0] = (Class) Integer.Type; //I found this out through doing some parsing Object[] object = new Object[1]; object[0] = param[0].newInstance();// This is where things fall apart. I don't want to use new Integer(0); for example.
🌐
CodeGym
codegym.cc › java blog › java classes › java.lang.integer class
Java.lang.Integer Class
February 20, 2025 - As a wrapper class, Integer provides various methods for working with int, as well as a number of methods for converting int to String and String to int. The class has two constructors: public Integer(int i), where i is a primitive value to ...
🌐
Codename One
codenameone.com › javadoc › java › lang › Integer.html
Integer (Codename One API)
Returns a new Integer object initialized to the value of the specified String. The first argument is interpreted as representing a signed integer in the radix specified by the second argument, exactly as if the arguments were given to the method. The result is an Integer object that represents ...
Top answer
1 of 6
42

new Integer(123) will create a new Object instance for each call.

According to the javadoc, Integer.valueOf(123) has the difference it caches Objects... so you may (or may not) end up with the same Object if you call it more than once.

For instance, the following code:

   public static void main(String[] args) {

        Integer a = new Integer(1);
        Integer b = new Integer(1);

        System.out.println("a==b? " + (a==b));

        Integer c = Integer.valueOf(1);
        Integer d = Integer.valueOf(1);

        System.out.println("c==d? " + (c==d));

    }

Has the following output:

a==b? false
c==d? true

As to using the int value, you are using the primitive type (considering your method also uses the primitive type on its signature) - it will use slightly less memory and might be faster, but you won't be ale to add it to collections, for instance.

Also take a look at Java's AutoBoxing if your method's signature uses Integer- when using it, the JVM will automatically call Integer.valueOf() for you (therefore using the cache aswell).

2 of 6
9

public static Integer valueOf(int i)

Returns a Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

Parameters:
i - an int value.
Returns:
a Integer instance representing i.
Since:
1.5

refer http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#valueOf%28int%29

This variant of valueOf was added in JDK 5 to Byte, Short, Integer, and Long (it already existed in the trivial case in Boolean since JDK 1.4). All of these are, of course, immutable objects in Java. Used to be that if you needed an Integer object from an int, you’d construct a new Integer. But in JDK 5+, you should really use valueOf because Integer now caches Integer objects between -128 and 127 and can hand you back the same exact Integer(0) object every time instead of wasting an object construction on a brand new identical Integer object.

private static class IntegerCache {
private IntegerCache(){}

static final Integer cache[] = new Integer[-(-128) + 127 + 1];

static {
    for(int i = 0; i < cache.length; i++)
    cache[i] = new Integer(i - 128);
}
}

public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
    return IntegerCache.cache[i + offset];
}
    return new Integer(i);
}

refer Why YOU should use Integer.valueOf(int)

EDIT

autoboxing and object creation:

The important point we must consider is that autoboxing doesn't reduce object creation, but it reduces code complexity. A good rule of thumb is to use primitive types where there is no need for objects, for two reasons:

Primitive types will not be slower than their corresponding wrapper types, and may be a lot faster. There can be some unexpected behavior involving == (compare references) and .equals() (compare values).

Normally, when the primitive types are boxed into the wrapper types, the JVM allocates memory and creates a new object. But for some special cases, the JVM reuses the same object.

The following is the list of primitives stored as immutable objects:

  • boolean values true and false

  • All byte values

  • short values between -128 and 127

  • int values between -128 and 127

  • char in the range \u0000 to \u007F

refer http://today.java.net/pub/a/today/2005/03/24/autoboxing.html#performance_issue

🌐
Scaler
scaler.com › home › topics › integer class in java
Integer Class in Java| Scaler Topics
April 14, 2024 - The java.lang.Integer class creates an object out of an int value. An object of type Integer has a single field with the type int.
🌐
Oracle
docs.oracle.com › en › java › javase › 20 › docs › api › java.base › java › lang › Integer.html
Integer (Java SE 20 & JDK 20)
July 10, 2023 - Constructs a newly allocated Integer object that represents the specified int value.
🌐
Medium
medium.com › @mohamadshahkhajeh › great-breakdown-of-how-javas-integer-object-creation-and-caching-mechanisms-work-6dd7f16be80c
Great breakdown of how Java's Integer object creation and caching mechanisms work!
April 16, 2025 - Great breakdown of how Java's Integer object creation and caching mechanisms work! 🧑‍💻 The subtle differences between new Integer() and Integer.valueOf() are often overlooked, but this …
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › lang › Integer.html
Integer (Java SE 11 & JDK 11 )
January 20, 2026 - Constructs a newly allocated Integer object that represents the specified int value.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.lang.integer.-ctor
Integer Constructor (Java.Lang) | Microsoft Learn
Constructs a newly allocated Integer object that represents the specified int value. [Android.Runtime.Register(".ctor", "(I)V", "")] public Integer(int value); [<Android.Runtime.Register(".ctor", "(I)V", "")>] new Java.Lang.Integer : int -> ...
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › lang › Integer.html
Integer (Java SE 21 & JDK 21)
January 20, 2026 - Constructs a newly allocated Integer object that represents the specified int value.