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..
}
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 ==.
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).
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.
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
orlong
, 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With