Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 477
Stefaan Neyts Avatar asked Oct 31 '22 05:10

Stefaan Neyts


1 Answers

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.

like image 54
Radiodef Avatar answered Nov 15 '22 06:11

Radiodef