有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

奇怪的Java行为。三元运算符

为什么这个代码可以工作

Float testFloat = null;
Float f = true ? null : 0f;

为什么这会引发异常

Float testFloat = null;
Float f = true ? testFloat : 0f;

但最奇怪的是,这段代码也成功运行,没有任何异常:

Float testFloat = null;
Float f = testFloat;

Java的三元运算符似乎改变了行为。有人能解释一下为什么会这样吗


共 (1) 个答案

  1. # 1 楼答案

    行为在JLS - Conditional Operator中指定:

    If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

    我的。因此,在2nd情况下:

    Float f = true ? testFloat : 0f;
    

    由于第三个操作数是基元类型(T),因此表达式的类型将是浮点类型-T。因此,取消绑定testFloat(当前是null引用)到float将导致NPE


    对于1st案例,相关部分为最后一部分:

    Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7).

    那么根据这个,

    null type - S1
    float     - S2
    
    null type - T1 (boxing null type gives null type)
    Float     - T2 (float boxed to Float)
    

    然后条件表达式的类型变为-Float。不需要对null进行拆箱,因此不需要NPE