Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Long object type with primitive int using ==

I have a method that returns a Long object datatype via invocation of: resp.getResultCode(). I want to compare it HttpStatus.GONE.value() which actually just returns a primitive int value of 410. Would the Long unbox itself to properly compare with the int primitive?

if(resp.getResultCode() == HttpStatus.GONE.value()){
  // code inside..
}
like image 759
user836087 Avatar asked Nov 05 '14 15:11

user836087


People also ask

Can we use == to compare long in Java?

equals() instead of the reference comparison operator (==). This is because Java maintains a constant pool for instances of Long between -128 and 127. This optimization, though, does not give us a license to use ==.

Can you use == to compare objects in Java?

In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables).

Can you compare long and int?

You can compare long and int directly however this is not recommended. Why is it not recommended? It is not better to cast long to integer before comparing, on the contrary, that can lead to overflow and thus to wrong results.


1 Answers

Here's the JLS explanation

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

and

If the promoted type of the operands is int or long, then an integer equality test is performed.

So the Long is unboxed to long. And numeric promotion is applied to int to make it a long. Then they are compared.

Consider that case where long would be "demoted" to an int, you'd have cases like this

public static void main(String[] args) throws Exception {
    long lvalue = 1234567891011L;
    int ivalue = 1912277059;
    System.out.println(lvalue == ivalue); // false
    System.out.println((int) lvalue == ivalue); // true, but shouldn't
}
like image 142
Sotirios Delimanolis Avatar answered Sep 28 '22 00:09

Sotirios Delimanolis