this is beacause from 1 to 127 values are stored somewhere in cash (you can think it like as string constant pool.) So once if a Integer object ranging from 1 to 127 is careted ,then when another object of same value needs to be created it will give the reference of the old object.
Indeed, class Integer has a caching mechanism, but this only works when you're getting Integer objects by calling Integer.valueOf(...), or by autoboxing a primitive int into an Integer (by doing this, Integer.valueOf(...) is implicitly called).
If you create new Integer objects explicitly, then two new Integer objects are created.
If you would do this:
1. Integer i1 = 127; 2. Integer i2 = 127;
Then i1 and i2 would both refer to the same Integer object.
Mr Jasper is right, As here new is being used to create the Integer object,hence whatever is the value(1-127 or higher) always a new obkect will be created.
I haven't really done a deeper study on Wrappers except for the ones discussed in the KB book. I have learned that wrappers are immutable though. Is the concept of immutability of Wrappers the same concept with that of Strings?
Thanks!
SCJP 5.0, SCWCD 5
Proudly marching to the beat of a different kettle of fish... while reading this tiny ad
a bit of art, as a gift, the permaculture playing cards