Why does the Java compiler sometimes allow the unboxing of null?

后端 未结 3 1167
梦谈多话
梦谈多话 2021-02-19 02:52

For example:

int anInt = null;

fails at compile time but

public static void main(String[] args) {
  for (int i = 0; i < 10;          


        
3条回答
  •  梦谈多话
    2021-02-19 03:07

    In the first case, the compiler knows that you're trying to unbox a compile-time constant of null.

    In the second case, the type of the conditional expression is Integer, so you're effectively writing:

    Integer tmp = new Random().nextBoolean() ? 1 : null;
    return (int) tmp;
    

    ... so the unboxing isn't happening on a constant expression, and the compiler will allow it.

    If you changed it to force the conditional expression to be of type int by unboxing there, it would fail:

    // Compile-time failure
    return new Random().nextBoolean() ? 1 : (int) null;
    

提交回复
热议问题