1

If we have expressions something like the following,

Integer x=500;
Integer y=500;

System.out.println(x==y);

then, the result of the operation x==y will be false because we are comparing the object references.


If I have a loop for these two variables x and y something like the following,

Integer x=0;
Integer y=0;

for(int i=0;i<2000;i++)
{
    System.out.println((x==y)+" : "+x+++" : "+y++);
}

then, it displays true until the value of both x and y is 127. In all other cases (i.e when the value of x and y is incremented over 127 - when the value of these variables is greater than 127).

So why does this happen? Is there any specification for this behaviour?

Tiny
  • 27,221
  • 105
  • 339
  • 599

2 Answers2

2

Integers of the values -128 through +127 are cached in the JVM.

Additionally, here is the Java Language Specification page about it. Specifically, Section 5.1.7 states

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

This is a case of boxing of primitive types and it is correct. Java Integers are cached using a flyweight pattern for values up to 128.

djechlin
  • 59,258
  • 35
  • 162
  • 290