三目运算符的一个坑-自动拆箱

本文探讨了在Java中使用三目运算符时可能会遇到的一个问题,即当条件表达式涉及自动拆箱时,可能会引发NullPointerException。通过示例代码`Integer b = true ? a : 0;`解释了该问题的产生原因及可能的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:
             Integer a = null;

             Integer b = true ? a : 0

执行这个三目表达式后, b等于多少, 理解原因;


执行以上两行代码

  1. /**
  2. * Created by ryan01.peng on 2017/7/25.
  3. */
  4. public class TestTernaryOperator {
  5. public static void main(String[] args) {
  6. Integer a = null;
  7. Integer b = true ? a : 0; //这里是第10行,报错行 b.intValue();
  8. System.out.println(b);
  9. }
  10. }
会导致报错,如下

  1. Exception in thread "main" java.lang.NullPointerException
  2. at com.vip.vcp.ryan.zhaunzheng.leBasic.TestTernaryOperator.main(TestTernaryOperator.java:10)
  3. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  4. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
  5. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  6. at java.lang.reflect.Method.invoke(Method.java:606)
  7. at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

分析:这里的报错出现在三目运算符所在的一行,而不是使用b的最后一行。说明这个NullPointerException并不是Integer b引起的,而是由于三目运算符所在行引起的。
这里空指针异常的原因是: 三目运算中只要后面两个元素是不同的类型,涉及到类型转换,那么编译器会往下(基本类型)转型,再进行运算。 就是说,如果运算中有int和Integer,Integer会先转成int再计算,在拆箱的过程中a=null转换成int,导致了NullPointerException。
我们将Integer b = true ? a : 0; 换为Integer b = true ? a : new Integer(0); 则不会抛出异常了。输出null

以后开发中避免的措施:
1. 对对象进行使用或者操作时都先验空,然后再进行操作处理。
2. 三目运算符后最好使用同种类型的对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值