Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to compare two `Integer` values with `==` in Java? [duplicate]

Tags:

java

I have this Java code:

public class Foo {
    public static void main(String[] args) {
         Integer x = 5;
         Integer y = 5;
         System.out.println(x == y);
    }
}

Is it guaranteed to print true on the console? I mean, is it comparing the two boxed integers by value (which is what I need to do) or by reference identity?

Also, will it be any different if I cast them to unboxed integers like this

public class Foo {
    public static void main(String[] args) {
         Integer x = 5;
         Integer y = 5;
         System.out.println((int) x == (int) y);
    }
}
like image 549
oggioniw Avatar asked Mar 14 '19 16:03

oggioniw


People also ask

Can I use == to compare integer in Java?

Java Integer compare() method public static int compare(int x, int y) Parameter : x : the first int to compare y : the second int to compare Return : This method returns the value zero if (x==y), if (x < y) then it returns a value less than zero and if (x > y) then it returns a value greater than zero.

Can we compare double with int Java?

It is valid, but you may get interesting results in edge cases if you don't specify a precision on the double...

How do you compare two Integers equal in Java?

To check two numbers for equality in Java, we can use the Equals() method as well as the == operator. Firstly, let us set Integers. Integer val1 = new Integer(5); Integer val2 = new Integer(5); Now, to check whether they are equal or not, let us use the == operator.

Can we use .equals for integer?

Integer Equals() method in JavaThe Equals() method compares this object to the specified object. The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.


1 Answers

No, it's not the right way to compare the Integer objects. You should use Integer.equals() or Integer.compareTo() method.

By default JVM will cache the Integer values from [-128, 127] range (see java.lang.Integer.IntegerCache.high property) but other values won't be cached:

Integer x = 5000;
Integer y = 5000;
System.out.println(x == y); // false

Unboxing to int or calling Integer.intValue() will create an int primitive that can be safely compared with == operator. However unboxing a null will result in NullPointerException.

like image 115
Karol Dowbecki Avatar answered Sep 21 '22 10:09

Karol Dowbecki