Consider the following code fragment:
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 1000;
Integer i4 = 1000;
System.out.println(i1==i2);
System.out.println(i3==i4);
Can you guess what will be printed on the screen? If your answer is false
--well, you're wrong.
In this case, J2SE 5.0 works differently. Certain ranges of values are stored as immutable objects by the Java Virtual Machine. So, in this case, the output is:
true
false
Normally, when the primitive types are boxed into the wrapper types, the JVM allocates memory and creates a new object. But for some special cases, the JVM reuses the same object.
The following is the list of primitives stored as immutable objects:
boolean
values true
and false
byte
values
short
values between -128 and 127
int
values between -128 and 127
char
in the range \u0000
to \u007F