Java quiz on Integer Comparison

What will be the output of following quiz on Integer Comparison ?

 
Java quiz on Integer Comparison

 

Answer

 
When we assign a literal number to Integer, compiler adds Integer.valueOf for the literal.

For example,

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, https:. All rights reserved. On republishing this post, you must provide link to original post

4 comments

  1. The result depends on the config, with the default config, the answer is correct

  2. ThunderFlash

    That was interesting, thanks for posting! I don’t compare objects with the equal sign, only with the {Objectname}.equals() function. That doesn’t use hacks like this 🙂

  3. Integer pool, one byte.

  4. Bernard FRANCIS

    “The high value up to which Integers are cached can be updated using the system property java.lang.Integer.IntegerCache.high”

    This is true starting as of JDK 7. JDK 5 and 6 threshold values are hard coded.

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: