Java 8 ternary operator 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; } } 

Method () has an int return type, which is a primitive type.

Consider the ternary operator used in the return statement:

  • it compiles using the default Java 8 compiler, but this will throw a NullPointerException at runtime, why?
  • using Maven this will lead to a compile-time error
 [ERROR] error: incompatible types: bad type in conditional expression [ERROR] <null> cannot be converted to int 

Can someone explain to me why it behaves differently?

+5
source share
2 answers

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

See Table 15.25-E. Type of conditional expression (3rd operand, part III) :

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

lub(Integer,null) must be an Integer . Basically, if you have a boolean form condition boolean ? int : null boolean ? int : null , the result of the expression must be Integer , and it becomes unboxed. (I think you already know this is happening.)

Thus, according to the specification, it should be the same.

Sounds like a compiler error. Many of them were discovered, I would say, try updating to the latest version.

+2
source

Not sure which version of Java 8 you are using, 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) 
0
source

All Articles