Jimmy's Blog

Integer, Byte, Long Constant Pool in Java

by jimmy on Aug.13, 2007, under English, Java, Programming

Following the topic about constant pool.
Let’s look inside the source code JDK 1.6, java\lang\Integer.java :

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);
}

From the source we can see when the value is -128 to 127 it’ll using cache / constant-pool.
So when we run the following code:

Integer i = 20;
Integer i2 = 20;
Integer i3 = 170;
Integer i4 = 170;
System.out.println(”i==i2 : ” + (i==i2) ); // true
System.out.println(”i==i2 : ” + (i3==i4) ); // false

Only value -128 until 127 will be cache. And of course the operator new wil create new object : new Integer(10)!=10.

Related posts:

  1. Java Constant Pool : String
  2. Java ME (J2ME) JSON Implementation For Array Object
  3. Java ME (J2ME) JSON Implementation Tutorial/Sample
  4. Java Application – Make sure only single/one instance running – with File Lock and ShutdownHook


Leave a Reply

Spam Protection by WP-SpamFree

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...