NullPointerException with autoboxing in ternary expression

后端 未结 4 1364
陌清茗
陌清茗 2020-12-03 02:50

Run the following Java code:

boolean b = false;
Double d1 = 0d;
Double d2 = null;
Double d = b ? d1.doubleValue() : d2;

Why is there a Null

4条回答
  •  无人及你
    2020-12-03 03:26

    Because the two expressions around : must return the same type. This means Java tries to convert the expression d2 to double. This means the bytecode calls doubleValue() on d2 -> NPE.

提交回复
热议问题