Integer caching in Java with new operatorWeird Integer boxing in JavaWhy aren't Integers cached in Java?Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?Efficiency of Java “Double Brace Initialization”?How do I convert a String to an int in Java?Creating a memory leak with JavaWhy don't Java's +=, -=, *=, /= compound assignment operators require casting?

Why was this sacrifice sufficient?

Looking for a simple way to manipulate one column of a matrix

Why does the Earth follow an elliptical trajectory rather than a parabolic one?

Guns in space with bullets that return?

Was the Highlands Ranch shooting the 115th mass shooting in the US in 2019

What are the ramifications of setting ARITHABORT ON for all connections in SQL Server?

Pre-1993 comic in which Wolverine's claws were turned to rubber?

Thesis' "Future Work" section – is it acceptable to omit personal involvement in a mentioned project?

We are two immediate neighbors who forged our own powers to form concatenated relationship. Who are we?

How can a Lich look like a human without magic?

Is there enough time to Planar Bind a creature conjured by a 1-hour-duration spell?

Does Lawful Interception of 4G / the proposed 5G provide a back door for hackers as well?

Will change of address affect direct deposit?

Two researchers want to work on the same extension to my paper. Who to help?

How do I tell my supervisor that he is choosing poor replacements for me while I am on maternity leave?

Make all the squares explode

How to pronounce "r" after a "g"?

Is the schwa sound consistent?

Set a camera to free fall like a Rigid Body?

51% attack - apparently very easy? refering to CZ's "rollback btc chain" - How to make sure such corruptible scenario can never happen so easily?

How to make a language evolve quickly?

How can this pool heater gas line be disconnected?

Why use steam instead of just hot air?

Was there ever any real use for a 6800-based Apple I?



Integer caching in Java with new operator


Weird Integer boxing in JavaWhy aren't Integers cached in Java?Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?Efficiency of Java “Double Brace Initialization”?How do I convert a String to an int in Java?Creating a memory leak with JavaWhy don't Java's +=, -=, *=, /= compound assignment operators require casting?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








18















In the below class I have tried to compare the wrapper class with the primitive but the results are different.



I have checked the following links links:




The more interesting question is why new Object(); should be required to create a unique instance every time? i. e. why is new Object(); not allowed to cache? The answer is the wait(...) and notify(...) calls. Caching new Object()s would incorrectly cause threads to synchronize with each other when they shouldn't.




If there is a new object then how are a and c equal?



If b is equal to c and c is equal to a, then a should be equal to b. But in following case I got a != c.



Please explain.



class WrapperCompare 

public static void main (String args[])
Integer a = new Integer(10);
Integer b = 10;
int c=10;
System.out.println(b==c); //true
System.out.println(a==b); //false
System.out.println(a==c); //true




Update:
By referring to this link Integer caching.




Basically, the Integer class keeps a cache of Integer instances in the range of -128 to 127, and all autoboxing, literals and uses of Integer.valueOf() will return instances from that cache for the range it covers.




So in this case all statements should be true.










share|improve this question



















  • 2





    Note that the constructor is deprecated and should not be used. Instead use valueOf.

    – Zabuza
    May 7 at 6:52






  • 5





    All but a==b here aren't comparing objects.

    – Andy Turner
    May 7 at 6:53






  • 5





    @Zabuza that's incorrect. new always returns a new instance. You only get the cached instances via valueOf (implicitly or explicitly).

    – Andy Turner
    May 7 at 6:54







  • 3





    The statement Integer b = 10; is equivalent to Integer b = Integer.valueOf(10); (and not Integer b = new Integer(10);)

    – Maurice Perry
    May 7 at 6:58







  • 1





    Good question, good answer, good comments. Good job everyone! :)

    – JollyJoker
    May 7 at 9:00

















18















In the below class I have tried to compare the wrapper class with the primitive but the results are different.



I have checked the following links links:




The more interesting question is why new Object(); should be required to create a unique instance every time? i. e. why is new Object(); not allowed to cache? The answer is the wait(...) and notify(...) calls. Caching new Object()s would incorrectly cause threads to synchronize with each other when they shouldn't.




If there is a new object then how are a and c equal?



If b is equal to c and c is equal to a, then a should be equal to b. But in following case I got a != c.



Please explain.



class WrapperCompare 

public static void main (String args[])
Integer a = new Integer(10);
Integer b = 10;
int c=10;
System.out.println(b==c); //true
System.out.println(a==b); //false
System.out.println(a==c); //true




Update:
By referring to this link Integer caching.




Basically, the Integer class keeps a cache of Integer instances in the range of -128 to 127, and all autoboxing, literals and uses of Integer.valueOf() will return instances from that cache for the range it covers.




So in this case all statements should be true.










share|improve this question



















  • 2





    Note that the constructor is deprecated and should not be used. Instead use valueOf.

    – Zabuza
    May 7 at 6:52






  • 5





    All but a==b here aren't comparing objects.

    – Andy Turner
    May 7 at 6:53






  • 5





    @Zabuza that's incorrect. new always returns a new instance. You only get the cached instances via valueOf (implicitly or explicitly).

    – Andy Turner
    May 7 at 6:54







  • 3





    The statement Integer b = 10; is equivalent to Integer b = Integer.valueOf(10); (and not Integer b = new Integer(10);)

    – Maurice Perry
    May 7 at 6:58







  • 1





    Good question, good answer, good comments. Good job everyone! :)

    – JollyJoker
    May 7 at 9:00













18












18








18


2






In the below class I have tried to compare the wrapper class with the primitive but the results are different.



I have checked the following links links:




The more interesting question is why new Object(); should be required to create a unique instance every time? i. e. why is new Object(); not allowed to cache? The answer is the wait(...) and notify(...) calls. Caching new Object()s would incorrectly cause threads to synchronize with each other when they shouldn't.




If there is a new object then how are a and c equal?



If b is equal to c and c is equal to a, then a should be equal to b. But in following case I got a != c.



Please explain.



class WrapperCompare 

public static void main (String args[])
Integer a = new Integer(10);
Integer b = 10;
int c=10;
System.out.println(b==c); //true
System.out.println(a==b); //false
System.out.println(a==c); //true




Update:
By referring to this link Integer caching.




Basically, the Integer class keeps a cache of Integer instances in the range of -128 to 127, and all autoboxing, literals and uses of Integer.valueOf() will return instances from that cache for the range it covers.




So in this case all statements should be true.










share|improve this question
















In the below class I have tried to compare the wrapper class with the primitive but the results are different.



I have checked the following links links:




The more interesting question is why new Object(); should be required to create a unique instance every time? i. e. why is new Object(); not allowed to cache? The answer is the wait(...) and notify(...) calls. Caching new Object()s would incorrectly cause threads to synchronize with each other when they shouldn't.




If there is a new object then how are a and c equal?



If b is equal to c and c is equal to a, then a should be equal to b. But in following case I got a != c.



Please explain.



class WrapperCompare 

public static void main (String args[])
Integer a = new Integer(10);
Integer b = 10;
int c=10;
System.out.println(b==c); //true
System.out.println(a==b); //false
System.out.println(a==c); //true




Update:
By referring to this link Integer caching.




Basically, the Integer class keeps a cache of Integer instances in the range of -128 to 127, and all autoboxing, literals and uses of Integer.valueOf() will return instances from that cache for the range it covers.




So in this case all statements should be true.







java instance equals






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 7 at 14:43









Boann

37.8k1291123




37.8k1291123










asked May 7 at 6:47









User12345User12345

14412




14412







  • 2





    Note that the constructor is deprecated and should not be used. Instead use valueOf.

    – Zabuza
    May 7 at 6:52






  • 5





    All but a==b here aren't comparing objects.

    – Andy Turner
    May 7 at 6:53






  • 5





    @Zabuza that's incorrect. new always returns a new instance. You only get the cached instances via valueOf (implicitly or explicitly).

    – Andy Turner
    May 7 at 6:54







  • 3





    The statement Integer b = 10; is equivalent to Integer b = Integer.valueOf(10); (and not Integer b = new Integer(10);)

    – Maurice Perry
    May 7 at 6:58







  • 1





    Good question, good answer, good comments. Good job everyone! :)

    – JollyJoker
    May 7 at 9:00












  • 2





    Note that the constructor is deprecated and should not be used. Instead use valueOf.

    – Zabuza
    May 7 at 6:52






  • 5





    All but a==b here aren't comparing objects.

    – Andy Turner
    May 7 at 6:53






  • 5





    @Zabuza that's incorrect. new always returns a new instance. You only get the cached instances via valueOf (implicitly or explicitly).

    – Andy Turner
    May 7 at 6:54







  • 3





    The statement Integer b = 10; is equivalent to Integer b = Integer.valueOf(10); (and not Integer b = new Integer(10);)

    – Maurice Perry
    May 7 at 6:58







  • 1





    Good question, good answer, good comments. Good job everyone! :)

    – JollyJoker
    May 7 at 9:00







2




2





Note that the constructor is deprecated and should not be used. Instead use valueOf.

– Zabuza
May 7 at 6:52





Note that the constructor is deprecated and should not be used. Instead use valueOf.

– Zabuza
May 7 at 6:52




5




5





All but a==b here aren't comparing objects.

– Andy Turner
May 7 at 6:53





All but a==b here aren't comparing objects.

– Andy Turner
May 7 at 6:53




5




5





@Zabuza that's incorrect. new always returns a new instance. You only get the cached instances via valueOf (implicitly or explicitly).

– Andy Turner
May 7 at 6:54






@Zabuza that's incorrect. new always returns a new instance. You only get the cached instances via valueOf (implicitly or explicitly).

– Andy Turner
May 7 at 6:54





3




3





The statement Integer b = 10; is equivalent to Integer b = Integer.valueOf(10); (and not Integer b = new Integer(10);)

– Maurice Perry
May 7 at 6:58






The statement Integer b = 10; is equivalent to Integer b = Integer.valueOf(10); (and not Integer b = new Integer(10);)

– Maurice Perry
May 7 at 6:58





1




1





Good question, good answer, good comments. Good job everyone! :)

– JollyJoker
May 7 at 9:00





Good question, good answer, good comments. Good job everyone! :)

– JollyJoker
May 7 at 9:00












1 Answer
1






active

oldest

votes


















25














Explanation



When you compare Integer vs int with ==, it needs to convert the Integer to an int. This is called unboxing.



See JLS§5.1.8:




If r is a reference of type Integer, then unboxing conversion converts r into r.intValue()




At that point, you are comparing int vs int. And primitives have no notion of instances, they all refer to the same value. As such, the result is true.



So the actual code you have is



a.intValue() == c


leading to a comparison of 10 == 10, both int values, no Integer instances anymore.



You can see that new Integer(...) indeed creates new instances, when you compare Integer vs Integer. You did that in a == b.




Note



The constructor new Integer(...) is deprecated. You should instead use Integer#valueOf, it is potentially faster and also uses an internal cache. From the documentation:




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.




The caching is important to note here, since it yields to == being true again (for cached values):



Integer first = Integer.valueOf(10);
Integer second = Integer.valueOf(10);
System.out.println(first == second); // true


The caching is guaranteed for values between -128 and +127, but may also be used for others.



Also note that your b actually comes out of the cache, since



Integer b = 10;
// same as
Integer b = Integer.valueOf(10);
// and not
Integer b = new Integer(10);


So boxing goes through Integers cache (see JLS§5.1.7).






share|improve this answer




















  • 2





    “it is much faster” is a too strong claim. As the documentation says, “this method is likely to yield significantly better space and time performance”, in other words, it enables potential optimizations, whether they exist, is implementation dependent.

    – Holger
    May 7 at 10:36











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56016969%2finteger-caching-in-java-with-new-operator%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









25














Explanation



When you compare Integer vs int with ==, it needs to convert the Integer to an int. This is called unboxing.



See JLS§5.1.8:




If r is a reference of type Integer, then unboxing conversion converts r into r.intValue()




At that point, you are comparing int vs int. And primitives have no notion of instances, they all refer to the same value. As such, the result is true.



So the actual code you have is



a.intValue() == c


leading to a comparison of 10 == 10, both int values, no Integer instances anymore.



You can see that new Integer(...) indeed creates new instances, when you compare Integer vs Integer. You did that in a == b.




Note



The constructor new Integer(...) is deprecated. You should instead use Integer#valueOf, it is potentially faster and also uses an internal cache. From the documentation:




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.




The caching is important to note here, since it yields to == being true again (for cached values):



Integer first = Integer.valueOf(10);
Integer second = Integer.valueOf(10);
System.out.println(first == second); // true


The caching is guaranteed for values between -128 and +127, but may also be used for others.



Also note that your b actually comes out of the cache, since



Integer b = 10;
// same as
Integer b = Integer.valueOf(10);
// and not
Integer b = new Integer(10);


So boxing goes through Integers cache (see JLS§5.1.7).






share|improve this answer




















  • 2





    “it is much faster” is a too strong claim. As the documentation says, “this method is likely to yield significantly better space and time performance”, in other words, it enables potential optimizations, whether they exist, is implementation dependent.

    – Holger
    May 7 at 10:36















25














Explanation



When you compare Integer vs int with ==, it needs to convert the Integer to an int. This is called unboxing.



See JLS§5.1.8:




If r is a reference of type Integer, then unboxing conversion converts r into r.intValue()




At that point, you are comparing int vs int. And primitives have no notion of instances, they all refer to the same value. As such, the result is true.



So the actual code you have is



a.intValue() == c


leading to a comparison of 10 == 10, both int values, no Integer instances anymore.



You can see that new Integer(...) indeed creates new instances, when you compare Integer vs Integer. You did that in a == b.




Note



The constructor new Integer(...) is deprecated. You should instead use Integer#valueOf, it is potentially faster and also uses an internal cache. From the documentation:




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.




The caching is important to note here, since it yields to == being true again (for cached values):



Integer first = Integer.valueOf(10);
Integer second = Integer.valueOf(10);
System.out.println(first == second); // true


The caching is guaranteed for values between -128 and +127, but may also be used for others.



Also note that your b actually comes out of the cache, since



Integer b = 10;
// same as
Integer b = Integer.valueOf(10);
// and not
Integer b = new Integer(10);


So boxing goes through Integers cache (see JLS§5.1.7).






share|improve this answer




















  • 2





    “it is much faster” is a too strong claim. As the documentation says, “this method is likely to yield significantly better space and time performance”, in other words, it enables potential optimizations, whether they exist, is implementation dependent.

    – Holger
    May 7 at 10:36













25












25








25







Explanation



When you compare Integer vs int with ==, it needs to convert the Integer to an int. This is called unboxing.



See JLS§5.1.8:




If r is a reference of type Integer, then unboxing conversion converts r into r.intValue()




At that point, you are comparing int vs int. And primitives have no notion of instances, they all refer to the same value. As such, the result is true.



So the actual code you have is



a.intValue() == c


leading to a comparison of 10 == 10, both int values, no Integer instances anymore.



You can see that new Integer(...) indeed creates new instances, when you compare Integer vs Integer. You did that in a == b.




Note



The constructor new Integer(...) is deprecated. You should instead use Integer#valueOf, it is potentially faster and also uses an internal cache. From the documentation:




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.




The caching is important to note here, since it yields to == being true again (for cached values):



Integer first = Integer.valueOf(10);
Integer second = Integer.valueOf(10);
System.out.println(first == second); // true


The caching is guaranteed for values between -128 and +127, but may also be used for others.



Also note that your b actually comes out of the cache, since



Integer b = 10;
// same as
Integer b = Integer.valueOf(10);
// and not
Integer b = new Integer(10);


So boxing goes through Integers cache (see JLS§5.1.7).






share|improve this answer















Explanation



When you compare Integer vs int with ==, it needs to convert the Integer to an int. This is called unboxing.



See JLS§5.1.8:




If r is a reference of type Integer, then unboxing conversion converts r into r.intValue()




At that point, you are comparing int vs int. And primitives have no notion of instances, they all refer to the same value. As such, the result is true.



So the actual code you have is



a.intValue() == c


leading to a comparison of 10 == 10, both int values, no Integer instances anymore.



You can see that new Integer(...) indeed creates new instances, when you compare Integer vs Integer. You did that in a == b.




Note



The constructor new Integer(...) is deprecated. You should instead use Integer#valueOf, it is potentially faster and also uses an internal cache. From the documentation:




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.




The caching is important to note here, since it yields to == being true again (for cached values):



Integer first = Integer.valueOf(10);
Integer second = Integer.valueOf(10);
System.out.println(first == second); // true


The caching is guaranteed for values between -128 and +127, but may also be used for others.



Also note that your b actually comes out of the cache, since



Integer b = 10;
// same as
Integer b = Integer.valueOf(10);
// and not
Integer b = new Integer(10);


So boxing goes through Integers cache (see JLS§5.1.7).







share|improve this answer














share|improve this answer



share|improve this answer








edited May 7 at 14:50

























answered May 7 at 6:57









ZabuzaZabuza

12.6k62945




12.6k62945







  • 2





    “it is much faster” is a too strong claim. As the documentation says, “this method is likely to yield significantly better space and time performance”, in other words, it enables potential optimizations, whether they exist, is implementation dependent.

    – Holger
    May 7 at 10:36












  • 2





    “it is much faster” is a too strong claim. As the documentation says, “this method is likely to yield significantly better space and time performance”, in other words, it enables potential optimizations, whether they exist, is implementation dependent.

    – Holger
    May 7 at 10:36







2




2





“it is much faster” is a too strong claim. As the documentation says, “this method is likely to yield significantly better space and time performance”, in other words, it enables potential optimizations, whether they exist, is implementation dependent.

– Holger
May 7 at 10:36





“it is much faster” is a too strong claim. As the documentation says, “this method is likely to yield significantly better space and time performance”, in other words, it enables potential optimizations, whether they exist, is implementation dependent.

– Holger
May 7 at 10:36



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56016969%2finteger-caching-in-java-with-new-operator%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?