rohan yadav wrote:Hi Niteen,
Integer Wrapper object will always be == when their primitive values are same and that value must fall between -127 to 128.
I would have to disagree with that. I think it is just a by-product of the compiler optimization rather than a guaranteed feature from the language spec. Consider my test code:
For String, I know the compiler will create a string pool for all the String literals and use the same instance from the pool if the code is refering to the same String literal. I think it is just the same case for autoboxed Integer wrapper. For manually created wrapper, it is obvious no compiler optimiation has been applied and they are not ==.
If we are autoboxing some value to one of the wrapper classes (Boolean, Byte, Short, Char, Integer, Long), the compiler sometimes creates a new object and sometimes uses the pool of values, similarly like with Strings.
autoboxing to Boolean and Byte always returns an object from the pool
autoboxing to Char, Short, Integer and Long returns an object from the pool when the autoboxed value is between -128 and 127 (inclusive)
autoboxing of Float and Double does not use the pool and always returns a new object
What a great explanation. Most of the books do not contain such explanations.
According to the explanation , the compiler has a cache of all the Integer objects between the range -128 to 127(Can we change the range?). So the reference variables i11(10) and i12(10) in the above example refer to the same Integer Object. But for the value 1000 two different Objects are created.
rohan yadav wrote:Can't believe you have done SCJP and SCWCD
Be Nice. Patil is SCJP 1.4 where this wasn't part of Java yet. SCWCD also does not include any information about auto(un)boxing. It is perfectly possible to get SCJP 1.4 and SCWCD 5 without any knowledge of auto(un)boxing, or any of the other features added in Java 5.0.