It is because Integer caching.
From java language specification 5.1.7
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.
Ideally, boxing a given primitive value p, would always yield an identical reference.
Integer i = Integer.valueOf(127);
Integer j = Integer.valueOf(127);
Both i
and j
point to same object. As the value is less than 127.
Integer k = Integer.valueOf(128);
Integer l = Integer.valueOf(128);
Both k
& l
point to different objects. As the value is greater than 127.
As, you are checking the object references using ==
operator, you are getting different results.
Update
You can use equals()
method to get the same result
System.out.println(i.equals(j));//equals() compares the values of objects not references
System.out.println(k.equals(l));//equals() compares the values of objects not references
Output is
true
true
==
operator checks the actual object references.
equals()
checks the values(contents) of objects.
Answer to comment
You have,
Integer i = Integer.valueOf(127);
Here new object is created & reference is assigned to i
Integer j = Integer.valueOf(127); //will not create new object as it already exists
Due to integer caching (number between -128 to 127) previously created object reference is assigned to j
, then i
and j
point to same objects.
Now consider,
Integer p = Integer.valueOf(127); //create new object
Integer q = Integer.valueOf(126); //this also creates new object as it does not exists
Obviously both checks using ==
operator and equals()
method will result false
. As both are different references and have different vales.