问题描述:
Integer a = null;
Integer b = true ? a : 0;
执行这个三目表达式后, b等于多少, 理解原因;
执行以上两行代码
/**
* Created by ryan01.peng on 2017/7/25.
*/
public class TestTernaryOperator {
public static void main(String[] args) {
Integer a = null;
Integer b = true ? a : 0; //这里是第10行,报错行
b.intValue();System.out.println(b);
}
}
会导致报错,如下
Exception in thread "main" java.lang.NullPointerException
at com.vip.vcp.ryan.zhaunzheng.leBasic.TestTernaryOperator.main(TestTernaryOperator.java:10)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
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. 三目运算符后最好使用同种类型的对象。