How comparison Object and primitive, with operator == works in Java?

For example:

Long objectLong = 555l;
long primitiveLong = 555l;

System.out.println(objectLong == primitiveLong); // result is true.

Is there invocation objectLong.longValue() method to compare Long to long or maybe some other way?

Jon Skeet
people
quotationmark

As ever, the Java Language Specification is the appropriate resource to consult

From JLS 15.21.1 ("Numerical Equality Operators == and !="):

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).

Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).

Then from 5.6.2 (binary numeric promotion):

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

  • If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).
  • [...]

So the Long is unboxed to a long. Your code is equivalent to:

Long objectLong = 555l;
long primitiveLong = 555l;

// This unboxing is compiler-generated due to numeric promotion
long tmpLong = objectLong.longValue();

System.out.println(tmpLong == primitiveLong); 

people

See more on this question at Stackoverflow