I have noticed that the following code when executed produces output: GOT ==. This I understand is because '==' return true for Integer instances if the primitive value is between 127 and -128.
But the same code if changed as the following does not pass the 'if' test:
Why is this so? Integer.valueOf() method returns an Integer object instance right? What is the difference between the 2?
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).
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:
The JDK itself isn't perfect...