Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Integer objects vs int

Tags:

java

I fixed an endless loop by changing Integer to int in the following:

public class IntTest {
    public static void main(String[] args) {
        Integer x=-1;
        Integer total=1000;

        while(x != total){
            System.out.println("x =" + x + "total ="+ total);
            x++;
        }
    }
}

What is the proper reason for this? I figured Integer would compare no problem.

Thanks.

like image 202
Trevor Avatar asked Oct 27 '10 17:10

Trevor


2 Answers

Because when you make != comparing on the object it compares the references. And the references between two objects in general case are different.

When you compare ints it always compares primitives, lets say not references( there are no objects ), but the values.

So, if you want to work with Integer you must use equals() on them.

Additionally, if your values are between 0 and 255 the comparison between Integer works fine, because of caching.

You can read here: http://download.oracle.com/javase/tutorial/java/data/numberclasses.html

like image 85
Vladimir Ivanov Avatar answered Oct 15 '22 11:10

Vladimir Ivanov


Integer is an Object, and objects are compared with .equals(..)

Only primitives are compared with ==

That's the rule, apart from some exceptional cases, where == can be used for comparing objects. But even then it is not advisable.

like image 23
Bozho Avatar answered Oct 15 '22 12:10

Bozho