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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值