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).

Answer from Marcelo on Stack Overflow
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

🌐
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 int value indicated by the String parameter.
Discussions

[Java] Why does new Integer(10) == new Integer(10) return false but 10 = new Integer(10) return true?
10 = new Integer(10) That should not compile. More on reddit.com
🌐 r/learnprogramming
12
1
January 12, 2017
java - create a new Integer object that holds the value 1? - Stack Overflow
To create a new Integer object that holds the value in java 1 which one of the following is right and what exactly is the difference in the following methods as all print the value? Method 1 : More on stackoverflow.com
🌐 stackoverflow.com
java - using new(Integer) versus an int - Stack Overflow
In the olden days (pre-Java 5), you could not do this: ... This is because 10 is just an int by itself. Integer is a class, that wraps the int primitive, and making a new Integer() means you're really making an object of type Integer. More on stackoverflow.com
🌐 stackoverflow.com
java - Integer i=3 vs Integer i= new Integer (3) - Stack Overflow
Notice that question was closed ... == new Integer(1), which isn't true. ... It's to do with how boxing works. From the JLS section 5.1.7: If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2. Basically, a Java implementation ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 ? Public class Demo { public static void main(String []args) { int val = 99; Integer obj = new Integer(val); ...
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › lang › Integer.html
Integer (Java Platform SE 7 )
The argument is interpreted as representing a signed decimal integer, exactly as if the argument were given to the parseInt(java.lang.String) method. The result is an Integer object that represents the integer value specified by the string. In other words, this method returns an Integer object equal to the value of: ... NumberFormatException - if the string cannot be parsed as an integer. ... 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.
🌐
CodeGym
codegym.cc › java blog › java classes › java.lang.integer class
Java.lang.Integer Class
February 20, 2025 - If you are unlucky enough to need an even larger number Java has you covered with BigInteger. 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 initialise.
🌐
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 - 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"); ...
Find elsewhere
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.

🌐
MIT
web.mit.edu › java_v1.0.2 › www › javadoc › java.lang.Integer.html
Class java.lang.Integer
Assuming the specified String represents an integer, returns a new Integer object initialized to that value. Throws an exception if the String cannot be parsed as an int.
🌐
GeeksforGeeks
geeksforgeeks.org › java › difference-between-an-integer-and-int-in-java
Difference between an Integer and int in Java with Examples - GeeksforGeeks
July 11, 2025 - Java 9 to Java 15: The code will compile and run, but using new Integer(String) will generate a deprecation warning.
🌐
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 - 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. Constructs a newly allocated Integer object that represents the specified int value.
🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › int-vs-Integer-java-difference-comparison-primitive-object-types
Integer vs. int: What's the difference?
August 3, 2025 - New Java 7 Features: Using String in the Switch ... – TheServerSide.com ... The key difference between the Java int and Integer types is that an int simply represents a whole number, while an Integer has additional properties and methods.
Top answer
1 of 9
18

It's to do with how boxing works. From the JLS section 5.1.7:

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Basically, a Java implementation must cache the boxed representations for suitably small values, and may cache more. The == operator is just comparing references, so it's specifically detecting whether the two variables refer to the same object. In the second code snippet they definitely won't, as new Integer(3) definitely isn't the same reference as any previously created one... it always creates a new object.

Due to the rules above, this code must always give the same result:

Integer x = 127;
Integer y = 127;
System.out.println(x == y); // Guarantee to print true

Whereas this could go either way:

Integer x = 128;
Integer y = 128;
System.out.println(x == y); // Might print true, might print false
2 of 9
6

Java pools integers between -128 and 127 and hence both the references are the same.

Integer i=3;
Integer j=3;

This results in autoboxing and 3 is converted to Integer 3. So for i is referring to an Integer object that is in constant pool, now when you do j=3, the same reference as that of i is assigned to j.

Whereas below code:

Integer j=new Integer(3);

always results in a new Integer creation, in heap. This is not pooled. And hence you see that both reference are referring to different objects. Which results in

Integer i=3;
Integer j=new Integer(3);
if(i==j)
   System.out.println("i==j"); // **does not print**
🌐
Oracle
docs.oracle.com › javame › config › cldc › ref-impl › cldc1.0 › jsr030 › java › lang › Integer.html
java.lang Class Integer
The resulting integer value is ... static Integer valueOf(String s, int radix) throws NumberFormatException · Returns a new Integer object initialized to the value of the specified String....
🌐
Coderanch
coderanch.com › t › 589353 › java › Integer-Integer
When to use Integer or new Integer (Java in General forum at Coderanch)
If it's really a String, I'd cast ... don't think I'd ever use your second form exactly like that. Agreed. One should never use the new keyword to convert to an Integer unless a new instance is required....
🌐
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 - 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. Constructs a newly allocated Integer object that represents the specified int value.
🌐
Runestone Academy
runestone.academy › ns › books › published › csawesome › Unit2-Using-Objects › topic-2-8-IntegerDouble.html
2.8. Wrapper Classes - Integer and Double — CSAwesome v1
The following Integer methods and constructors, including what they do and when they are used, are part of the Java Quick Reference. Integer(value): Constructs a new Integer object that represents the specified int value.
🌐
Study.com
study.com › business courses › business 104: information systems and computer applications
Java Integer: Definition & Examples | Study.com
In this lesson, we'll take a look at integers in Java and give some examples of integers and the code for them. At the end, you should have a good...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-lang-integer-class-java
Java.lang.Integer class in Java - GeeksforGeeks
June 21, 2022 - If we assign x = 200 or x=300 next time, it will point to the value 200 or 300 which is present already in space of constants. If we assign values to x other than these two values, then it creates a new constant. (Check the Integer wrapper class comparison topic for better understanding)