天天看点

java 返回布尔值,java-当返回使用三元运算符时,返回布尔值的方法仍如何编译?...

这个问题已经在这里有了答案:            >            Booleans, conditional operators and autoboxing                                    4个

该代码如何编译?我本来希望编译器抱怨“类型不匹配:无法从null转换为boolean”,但事实并非如此.它只是在运行时失败,并显示NullPointerException.

public static void main(String[] args) throws Exception {

System.out.println("this throws a NPE: " + whyIsThisPossible(1, 2));

}

private static boolean whyIsThisPossible(int a, int b) {

return a + b == 2 ? true : null;

}

Exception in thread "main" java.lang.NullPointerException

at FunkyMethodTest.whyIsThisPossible(FunkyMethodTest.java:10)

at FunkyMethodTest.main(FunkyMethodTest.java:5)*

解决方法:

Java认为三元表达式的类型为布尔值.编译器将null视为布尔值,即对原始类型的boolean应用装箱转换的结果.

这是语言规范的相关部分:

15.25 The type of a conditional expression is determined as follows:

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.

语言规范指出,装箱/拆箱转换在必要时应用于表达式条件所选择的操作数.这就是当代码尝试从null中取消布尔值时触发异常的原因.

标签:java

来源: https://codeday.me/bug/20191110/2014599.html