NullPointerException in ternary expression with null Long

前端 未结 2 605
猫巷女王i
猫巷女王i 2021-01-11 19:29

Why does the following line of code produce a NullPointerException?

Long v = 1 == 2 ? Long.MAX_VALUE : (Long) null;

I understa

2条回答
  •  渐次进展
    2021-01-11 20:01

    So it looks obvious that you only have to box if the condition is true, and there should be no boxing if the condition is false. However the ternary operator expression must have a particular static type. So we have Long and long. The JLS states that the result will be the primitive (just as well - imagine if the operator was, say, + or even ==). So the ternary operator will force the unboxing, and only then does the assignment cause a boxing.

    If you were to replace the code with the equivalent if-else, then you'd just have an assignment from long to Long and from Long to Long, which wouldn't have any unboxing and so run fine.

    IIRC, this is covered is Bloch & Gafter's Java Puzzlers.

提交回复
热议问题