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 › create-an-integer-object-in-java
Create an Integer object in Java
December 18, 2024 - In this example, we will create ... Inetger.parseInt(str); System.out.println(obj); } } ... A string containing a valid integer value, such as "10", can be used to create an Integer object....
🌐
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 ...
🌐
CodeGym
codegym.cc › java blog › java classes › java.lang.integer class
Java.lang.Integer Class
February 20, 2025 - As a wrapper class, Integer provides ... to String and String to int. The class has two constructors: public Integer(int i), where i is a primitive value to initialise. This one creates an Integer object that is initialised with the ...
🌐
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. The Java Integer class has methods to convert an int to a String and vice-versa, as well as various constants(MAX_VALUE,MIN_VALUE, SIZE,TYPE) and methods that deal ...
🌐
LabEx
labex.io › tutorials › java-how-to-create-integer-wrapper-object-420416
How to create Integer wrapper object | LabEx
This tutorial explores various methods of creating Integer objects, demonstrating the flexibility and power of Java's wrapper classes in handling integer values.
Find elsewhere
🌐
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. The string is converted to an int value in exactly the manner used by the parseInt method for radix 10.
🌐
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. ... Returns the value of this Integer as a double. ... Compares this object to the specified object.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-lang-integer-class-java
Java.lang.Integer class in Java - GeeksforGeeks
June 21, 2022 - Integer(String s): Creates an Integer object initialized with the int value provided by string representation. Default radix is taken to be 10.
🌐
Tutorialspoint
tutorialspoint.com › java › lang › java_lang_integer.htm
Java - Integer class
This class inherits methods from ... args) { // create a String s and assign value to it String s = "+120"; // create a Integer object i Integer i; // get the value of int from string i = Integer.valueOf(s); // print the value ...
🌐
Udemy
blog.udemy.com › home › working with the integer class in the java programming language
Working with the Integer Class in the Java Programming Language - Udemy Blog
December 4, 2019 - If a class explicitly declares ... is created. Learn about various Java concepts through a course at Udemy.com ... When the Integer class loads, this constructor allocates an Integer object for the int value that is passed as argument. In Java 5.0 and later, the integer object can be directly assigned to an int ...
🌐
Quora
quora.com › How-do-I-create-user-defined-Integer-class-in-Java
How to create user defined Integer class in Java - Quora
Answer (1 of 2): You cannot create user defined Integer class in java because its final Integer class cannot be extended because its defined final in Java SDK Same case is for String class which is also final and cannot be extended by another class and override any of functionality Java has do...
🌐
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. The string is converted to an int value in exactly the manner used by the parseInt method for radix 10.
🌐
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
Find and fix the bugs below to use the correct Integer and Double methods and variables. The Integer class and Double class are wrapper classes that create objects from primitive types. The following Integer methods and constructors, including what they do and when they are used, are part of the Java Quick Reference.
🌐
Brainly
brainly.com › computers and technology › high school › you can create an integer object from an integer by using the integer constructor with the int argument. true or false?
[FREE] You can create an Integer object from an integer by using the Integer constructor with the int argument. - brainly.com
May 16, 2023 - True. You can create an Integer object from an integer by using the Integer constructor with the int argument. The Integer class in Java provides constructors that allow you to create Integer objects from primitive int values.
🌐
Coderanch
coderanch.com › t › 405057 › java › Setting-Integer-object
Setting value of Integer object (Beginning Java forum at Coderanch)
As you rightly suggest, the preferred way to return MRVs in Java is to create and return a custom object, setting the values in the called function, and then 'getting' those values after returning. This is obviously required for when the return values are of different types. In my case though, I really wanted 2 integers to be returned so your example using an array is very useful.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.lang.integer
Integer Class (Java.Lang) | Microsoft Learn
[<Android.Runtime.Register("java/lang/Integer", DoNotGenerateAcw=true)>] type Integer = class inherit Number interface IConvertible interface IComparable interface IJavaObject interface IDisposable interface IJavaPeerable ... The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. In addition, this class provides several methods for converting an int to a String and a String to an int, as well as other constants and methods useful when dealing with an int.