Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification regarding Integer comparison? [duplicate]

class Demo{
public static void main(String[] args) {  
     Integer i = Integer.valueOf(127);  
     Integer j = Integer.valueOf(127);        

     System.out.println(i==j);  

     Integer k = Integer.valueOf(128);  
     Integer l = Integer.valueOf(128);        

     System.out.println(k==l);  
  }  
}

The first print statement prints true whereas the second one prints false.Why? Please explain in detail.

like image 399
Prasoon Mishra Avatar asked Sep 15 '26 06:09

Prasoon Mishra


1 Answers

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  
  1. == operator checks the actual object references.
  2. 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.

like image 121
Aniket Kulkarni Avatar answered Sep 17 '26 20:09

Aniket Kulkarni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!