NullPointerException in ternary expression with nu

2019-02-16 19:53发布

Why does the following line of code produce a NullPointerException?

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

I understand that unboxing is being performed on null, but why?

Note that

Long v = (Long) null;

Does not produce the Exception.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-02-16 20:22

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.

查看更多
闹够了就滚
3楼-- · 2019-02-16 20:25

From the JSL

  1. If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression.
  2. If one of the second and third operands is of type boolean and the type of the other is of type Boolean, then the type of the conditional expression is boolean.

In following statement the type of second operand is long and third is Long.

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

This will work if an expression is true.

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

Or you may cast it.

Long v= 1 == 2 ?  Long.valueOf(Long.MAX_VALUE) : (Long) null;
查看更多
登录 后发表回答