I am not able to understand how the Java Constant Pool for Integer works.
I understand the behavior of Strings, and hence able to justify myself that it is the same case with Integer Constants also.
So, for Integers
Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1==i2); // True
&
Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
System.out.println(i1==i2); // False
Till here everything goes in my head.
What I am not able to digest is, it behaves differently when I increase the integer from 127. This behavior changes after 127, below is the code snippet
Integer i1 = 128;
Integer i2 = 128;
System.out.println(i1==i2); // False. WHY?????
Can somebody help me understand this?
No, the constant pool for numbers doesn’t work the same way as for strings. For strings, only compile-time constants are interned – whereas for the wrapper types for integer types, any boxing operation will always use the pool if it’s applicable for that value. So for example:
The JLS guarantees a small range of pooled values, but implementations can use a wider range if they wish.
Note that although it’s not guaranteed, every implementation I’ve looked at uses
Integer.valueOfto perform boxing operations – so you can get the same effect without the language’s help:From section 5.1.7 of the JLS: