Alex Rivera | Logout

Integers caching in Java

Asked 2010-06-28T09:01:39.217
64

Possible Duplicate:
Weird Java Boxing

Recently I saw a presentation where was the following sample of Java code:

Integer a = 1000, b = 1000;  
System.out.println(a == b); // false  
Integer c = 100, d = 100;  
System.out.println(c == d); // true

Now I'm a little confused. I understand why in first case the result is "false" - it is because Integer is a reference type and the references of "a" and "b" is different.

But why in second case the result is "true"?

I've heard an opinion, that JVM caching objects for int values from -128 to 127 for some optimisation purposes. In this way, references of "c" and "d" is the same.

Can anybody give me more information about this behavior? I want to understand purposes of this optimization. In what cases performance is increased, etc. Reference to some research of this problem will be great.

Edit
Report

1 Answer

14

Look at the implementation of Integer.valueOf(int). It will return the same Integer object for inputs less than 256.

EDIT:

It's actually -128 to +127 by default as noted below.

answered 2010-06-28T09:06:38.403

Your Answer