They are equal because they both represent the number 100. They are both different objects though, since autoboxing only uses cached values for -128 to 127. Everything outside that range will actually return a new Integer object.
I ran the code and sure enough both ifs expressions resulted true as expected: they are both completely different objects but their values are meaningfully equal.
Taking into account Rob´s reply, if you modify 1000 with 100 or some low enough value then both Integer references will point to the same object in memory. I am not sure either if this -127...128 range of "cached values" is the only valid one for all JVMs, but it is certainly the range used on my local machine.
what are cached values are they same as predefined values?? and what is JLS??
Joined: Oct 13, 2005
JLS is the Java™ Language Specification; I posted a link to it yesterday. You will have to look about cached values in that link.
I don't think it actually says what happens, whether the cached values are predetermined rather like eager instantiation, nor whether they are set up at the time they are used, like a sort of lazy instantiation.
salvin francis wrote: . . . When I ran it, it worked fine . . .
When I did the "Advanced Java" module, one of the people had some Strings to compare with the ==. In C# that operator is overloaded for Strings, so that works in C#.There were many Strings to compare, and of course it worked . . . because they were assigned from String literals. Then after serializing and de-serializing the whole object, all the Strings which had been referring to literals didn't any more.
So you can get things which work when you use == on Strings, and can break mysteriously later on.