Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected result when comparing ints [duplicate]

Tags:

java

Possible Duplicate:
Integer wrapper objects share the same instances only within the value 127?
How != and == operators work on Integers in Java?

I tried to compare two ints with the following cases and got unexpected results

  1. when I did the following, @@@ was printed.

     class C {
       static Integer a = 127;
       static Integer b = 127;
       public static void main(String args[]){
       if(a==b){
          System.out.println("@@@"); 
       }
       }
     }
    
  2. when I did the following, @@@ was not printed.

     class C {
       static Integer a = 145;
       static Integer b = 145;
       public static void main(String args[]){
       if(a==b){
          System.out.println("@@@"); 
       }
       }
     }
    

Can anyone tell me what could be the reason.

like image 680
Rookie Avatar asked Aug 30 '12 21:08

Rookie


4 Answers

You're comparing the objects' identities. For values lower than 128 the Integer class caches its objects. That's why it is equal in the first example. The other example is with higher values that are not cached.

As @niklon pointed out there is also a lower border of -128 for caching.

Upper border can be adjusted with a VM arg -Djava.lang.Integer.IntegerCache.high=4711.

Further reading in Peter's interesting blog post: http://vanillajava.blogspot.co.uk/2012/01/surprising-results-of-autoboxing.html

like image 53
Fabian Barney Avatar answered Sep 17 '22 14:09

Fabian Barney


You're not comparing ints, you're comparing objects for reference equality. Use .equals, or use type int instead of Object.

like image 37
Mike Samuel Avatar answered Sep 18 '22 14:09

Mike Samuel


Here you are using Integer objects as opposed to int primitives. Hence, you should compare the two instances with .equals(...) as opposed to ==. If you used the primitive type instead, you would use ==.

It is important to note that, when dealing with objects, == compares the references of the two objects, not the actual values - so it may return seemingly strange results at times.

like image 40
arshajii Avatar answered Sep 17 '22 14:09

arshajii


Use if(a.equals(b)) and do not use == to compare Objects that are subclasses of Object class.

== operator is just for primitive types like int,long, etc.

like image 32
Mehdi Avatar answered Sep 18 '22 14:09

Mehdi