Christophe Verré wrote:In both case, they will be unboxed and their int value will be compared.
I do not think this is true.
Did you try to compile and run the code? I tried your code (on Java 6 update 22, on Windows), and it prints "Different Objects", but it does not print "Same Objects".
In the if-statements in your code, it just compares the references. Since i1 and i2 refer to different Integer objects, you'll get "Different Objects", and not "Same Objects".
Unboxing will only be done when the compiler has a reason to do it - for example when you compare an Integer to an int variable, or to a literal numeric value. When comparing two Integer variables, the compiler can do the comparison by comparing references, so it doesn't have a reason to do unboxing.
Try the System#identityHashCode method on those two Integer objects. There is caching of Integers, rather like Strings; it is mandatory for values in the range -128 ... 127 inclusive, but somewhere (I think the Java™ Language specification, But I can't find it in the index) it says the recommendation is for as many Integers as possible to be cached. It is possible that the newer JVMs are caching more Integers than -128..127. Your 1000 is a compile-time constant, so the compiler can recognise those are both the same value. The boxing creation of an Integer uses the valueOf() method, as you can see from this bytecode . . . and the valueOf link I posted tells you that frequently used values are cached.
Thank you Campbell
It was interesting to know this answer ,
There was a mistake from my side actually i compared Integer i1 = 10 and Integer i2 = 10 apart from book where it was given 1000
and so the value is been cached and hence != evaluated to false .
Yes and when i tried it for values 128 it wasn't cached , but for 127 it was .
Also I haven't read the JLS and thankyou very much for this answer it cleared the doubt to a deeper extent .
Seetharaman Venkatasamy wrote:In contrast to == and !==, operators such as <, >, + are unbox the wrapper objects before performing their operation.
Yes. It is done this way because only != and == can be applied to instances. The other operators must operate on a numerical value, which can be obtained only by unboxing.
The correct test to see whether == and != on Integers performs unboxing or not must make sure the two instances are different, eg. by calling a constructor explicitly (this is, by the way, generally discouraged, because the caching mechanism is circumvented):