NullPointerException in ternary expression with null Long

前端 未结 2 608
猫巷女王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

    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;
    

提交回复
热议问题