Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primitive and Object comparison with == operator

I am wondering what is the internal Java behaviour for the next snippet:

Long a = 123L;
long b = 123;
System.out.println("a equals b?: " + (a == b));

The result is true although comparing two Long objects would be false (because it compares their reference). It is Java converting Long object into its primitive value because detects == operator against another primitive object?

like image 497
elegarpes Avatar asked Mar 14 '23 21:03

elegarpes


1 Answers

It is Java converting Long object into its primitive value because detects == operator against another primitive object?

Yes. One of the operands is a primitive type and the other operand is convertible to a primitive by unboxing.

JLS section 15.21.1 says (emphasis mine):

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

Also, it is important to note that reference equality is only performed if both operands are objects. JLS section 15.21.3 says:

If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.

like image 152
Tunaki Avatar answered Mar 23 '23 13:03

Tunaki