1

Possible Duplicate:
How != and == operators work on Integers in Java?

Integer i1 = 1000; Integer i2 = 1000;

if(i1 == i2) is return false. Exactly what it happen how it is checking this condition here?

if i assign lesser than 128 in both i1 and i2 if condition is true. How object is created here, it is comman for all the values or different? Could someone clarify this scenario.

Community
  • 1
  • 1
Venkat
  • 11
  • 1
  • For additional information http://vanillajava.blogspot.co.uk/2012/01/surprising-results-of-autoboxing.html#!/2012/01/surprising-results-of-autoboxing.html – Peter Lawrey Dec 18 '12 at 11:31
  • Integers in the range -128 and 127 are cached when boxing as of [5.1.7. Boxing Conversion](http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7) of the JLS. – Xavi López Dec 18 '12 at 11:31
  • For object comparison you should use equals method – Sree Dec 18 '12 at 11:35

1 Answers1

3

if i assign lesser than 128 in both i1 and i2 if condition is true

Yes this happens because for that range Java uses flyweight pattern and caches Integer objects so you get backed the cached version and == works
This is possible as Integer objects are immutable and the caching is only for the range [-128,127]

Cratylus
  • 52,998
  • 69
  • 209
  • 339