隐式转换和自动封箱

来源:互联网 发布:mcst指标源码 编辑:程序博客网 时间:2024/04/27 14:19
    public static void main(String[] args){     Integer a = null;        Integer b = true ? a : 0;      Integer c = true ? a : Integer.valueOf(0);      }


Integer b = true ? a : 0;

编译通过,运行时抛出NullPointerException,原因就在于在运行期整个三目表达式认为a的程序类型为Integer,而0的程序类型为int,并自动进行了隐式的类型转换,试图将a转化为int,很明显这导致了错误的发生。

 

Integer c = true ? a : Integer.valueOf(0);

编译通过,运行正常,通过强制类型转换避免自动封箱.

原创粉丝点击