What will be the output of following quiz on Integer Comparison ?
When we assign a literal number to Integer, compiler adds Integer.valueOf for the literal.
Integer i1= -128 becomes Integer i1= Integer.valueOf(-128)
In valueOf implementation, by default integers -128 to 127 are cached and the cached instance is returned for the integer.
Therefore i1==i2 returns true as they are referring to same cached instance.
However, 128 is not cached, so i3==i4 returns false.
The default high value until which integers are cached is 127. So, values from -128 till 127 is cached.
The high value up to which Integers are cached can be updated using the system property java.lang.Integer.IntegerCache.high
Correct answer is “true,false”
© 2016, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post