Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it legal to compare Objects and primitives with '==' operator?

Is the below (Java) code legal?

class Test {
  Object foo() {return "";}
  boolean bar() {return foo() == true;}
}

It won't compile against JDK 6 but seems fine on 7+. Did the spec change? Was a bug fixed? I've been discussing at http://bugs.eclipse.org/bugs/show_bug.cgi?id=416950 and could go either way on this one.

like image 688
Hollis Waite Avatar asked Sep 11 '13 01:09

Hollis Waite


1 Answers

JLS about reference equality doesn't change between java 6 & 7:

Chapter 15.21.3: Reference Equality Operators == and != :

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

It is a compile-time error if it is impossible to convert the type of either operand to the type of the other by a casting conversion (§5.5). The run-time values of the two operands would necessarily be unequal.

However I noticed some change on Chapter 5.5: Casting Conversion. Casting boolean to Object appears to be classified as boxing convention on Java 7:

An expression of a primitive type may undergo casting conversion to a reference type without error, by boxing conversion.

enter image description here

⊡ signifies boxing conversion

Hence since the primitive true can be casted to Object, your equality expression can be classified as reference equality on Java 7, and doesn't yield compiler error

like image 170
gerrytan Avatar answered Sep 28 '22 00:09

gerrytan