Wednesday, May 23, 2007

Weird Integer

Take a look at this simple class :

class Werid
{
public static void main(String args[])
{
Integer j1 = 127;
Integer j2 = 127;
System.out.println(j1==j2); // true

Integer k1 = 128;
Integer k2 = 128;
System.out.println(k1==k2); // false
}
}

How do you think, is it all OK here ? :) There is _something_ in this class. I've noticed that for the numbers less than 128 operator == returns true.
Why ?..

Lets see... When we run our Werid class with -verbose option we'll get sometting like this :

C:\>java -verbose Werid
.......
.......
[Loaded Werid from file:/C:/]
[Loaded java.lang.Integer$IntegerCache from shared objects file]
true
true
false
false
.......
.......
OK. What we have at java.lang.Integer$IntegerCache ? Cache of Integers is something interesting already. Lets go to sources :
private static class IntegerCache {
private IntegerCache(){}
static final Integer cache[] =
new
Integer[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}
Great, it really cache. It is used only in one method:
/**
* Returns a Integer instance representing the
specified
int value.
* If a new Integer instance is not required,
this method
* should generally be used in preference to
the constructor

* {@link #Integer(int)}, as this method is likely
to yield

* significantly better space and time performance
by caching

* frequently requested values.
*
* @param i an int value.
* @return a Integer instance representing
i.
* @since 1.5
*/
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
Ahaa :) if (i >= -128 && i <= 127).
Things become more clear now.

2 comments:

Anonymous said...

Interesting and useful research.

Keep it up.

Thanks
Rajesh Vaghela
SoftCrop Technology

Stas Ostapenko said...

Rajesh, Thanks for comment !

I'm doing my best :)