Object with primitive type equality operator and Java Language specification
Alex Buckley
alex.buckley at oracle.com
Mon Jul 13 18:32:47 UTC 2015
The JLS section on == is rather stable, and has always rejected the code
below. Object isn't convertible to a numeric type, and int isn't a
reference type, and either type is boolean or Boolean, so no equality
operator is available.
javac historically had some problems with operators taking Object and a
numeric type (or rather, taking expressions of those types), but I
believe this was cleaned up a couple of years ago, and JDK 8 correctly
rejects the code below.
FWIW, if you cast num to Object to the right of == (legal by JLS8 5.5),
then JDK 8 correctly compiles the code. The output is 'true' because of
the flyweight pattern applied to boxed integer literals between -128 and
127. If you make both integer literals in the code be 128, then the
output is 'false'.
Alex
On 7/13/2015 11:09 AM, Rostislav Krasny wrote:
> Hi,
>
> javac of JDK7 successfully compiles a code like following:
>
> public class MainClass {
>
> private static Object getValue() {
> return 123;
> }
>
> public static void main(String[] args) {
> int num = 123;
>
> System.out.println(getValue() == num);
> }
> }
>
> I believe javac of other JDKs, starting from JDK5, also compile such a
> code without any problem. However Eclipse and its Java compiler fails to
> compile the Object with primitive type equality (getValue() == num) with
> an error "Incompatible operand types Object and int". There is a bug
> report about this in the Eclipse Bugzilla:
>
> https://bugs.eclipse.org/bugs/show_bug.cgi?id=405732
>
> This bug was closed as NOT_ECLIPSE, i.e. developers of Eclipse Java
> compiler believe their compiler do it right. Please read the discussion
> in that bug report.Specifically Stephan Herrmann stated that Java
> Language specification disallows compiling such a code. So is it a bug
> in the javac compiler itself? Or maybe the JLS needs to be changed to
> conform to the long ago adopted javac compiler implementation? Or there
> is the JLS misunderstanding?
>
> Thanks
More information about the compiler-dev
mailing list