Jisha Anand wrote:Why is this so? Integer.valueOf() method returns an Integer object instance right? What is the difference between the 2?
Yes, but note that there are two versions of the valueOf() method in class Integer: one that takes an int, and one that takes a String. Only the version that takes an int makes use of the internal cache that contains Integer objects for all values between -128 and 127. The version that takes a String always creates a new Integer object. (This was discussed in another topic recently, and I was surprised that it works like this - but it really does, you can have a look at the source code of class Integer which you will find in src.zip in your JDK installation directory to see it yourself).
Integer.valueOf("-128") creates a new Integer object.
Integer smallS = -128 uses autoboxing, which means the compiler automatically translates it to: Integer smallS = Integer.valueOf(-128). Note that this uses the int version of the valueOf() method.
You now have to separate Integer objects, and comparing them with == will give false because == compares references (not values) when used on objects.
It's sort of the same as with strings, but in the case of strings, the compiler itself handles them in a special way, while with class Integer, it's just the implementation of that class that does it (the compiler doesn't need to do anything special).
Jisha Anand wrote:Just out of curiosity; why this discrimination? Is there any reason why the integer objects created by passing String doesn't get the benefit of internal cache?
I don't know, if you look at the String version of the valueOf() method, it looks like this:
It would have been better if it was like this, so that it would take advantage of the cache: