Ternary operator in Java 8, compilation with Maven

Consider this class:

package be.duo.test; public class Main { public static void main(String[] args) { Main main = new Main(); main.execute(); } private void execute() { for(int i = 0; i < 10; i++) { System.out.println("" + method()); } } private int method() { return (Math.random() > 0.5d) ? 1 : null; } }

The method() has return type int, which is a primitive type.

Consider the ternary operator used in the return statement:

  • it compiles with the Java 8 default compiler, but this will result in a NullPointerException at runtime, why?
  • using Maven this will result in a compile time error

[ERROR] error: incompatible types: bad type in conditional expression [ERROR] <null> cannot be converted to int

Can somebody explain to me why it behaves different?

-------------Problems Reply------------

As far as I can tell, it should be legal under Java 8.

See Table 15.25-E. Conditional expression type (Reference 3rd operand, Part III):

3rd → null
2nd ↓
int lub(Integer,null)

lub(Integer,null) should be Integer. Basically if you have a conditional of the form boolean ? int : null, the result of the expression should be Integer and it gets unboxed. (I think you already know this is what happens.)

So according to the specification it should be the same.

Seems like a compiler bug. There have been quite a few of these found, I would say try updating to the newest version.

Not sure which Java 8 minor version you use, but i can compile under java 1.8.

C:\Users\XXXX>javac -version
javac 1.8.0_31

C:\Users\XXXX>javac Main.java

C:\Users\XXXX>java Main
Exception in thread "main" java.lang.NullPointerException
at Main.method(Main.java:15)
at Main.execute(Main.java:10)
at Main.main(Main.java:5)

Category:java Views:4 Time:2016-06-18

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.115 (s). 11 q(s)