Comparing Long object type with primitive int using ==
Asked Answered
I

1

6

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..
}
Incursive answered 5/11, 2014 at 15:49 Comment(3)
Yes and the int will be promoted to a long value.Phobos
@SotiriosDelimanolis: That's an answer, not a comment. :-)Franzoni
really? Why does it do that? that's surprising that the int would be promoted. I thought behind the scenes, the Long would be casted to an int.Incursive
P
11

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
}
Phobos answered 5/11, 2014 at 15:53 Comment(3)
The reason why that works is because the lower 32 bits are the same for both numbers. The demotion strips the upper bits of the long value; which is the reason why it should not be done.Animalist
Hi, where do I learn the knowledge for being able to understand what hfontanez said about bits and bytes? I'm not a CS guy, I studied music. I'm a musical programmer now. ;-)Incursive
@Incursive That's kind of a broad subject. Start at wikipedia on binary numbers. Then review how primitive numerical types are represented in Java (if that's what you'll be using).Phobos

© 2022 - 2024 — McMap. All rights reserved.