美文网首页
java三元表达式转换规则

java三元表达式转换规则

作者: 别拿爱情当饭吃 | 来源:发表于2019-07-30 16:39 被阅读0次

代码如下

public class Parsing {
    /**
     * Returns Integer corresponding to s, or null if s is null.
     * @throws NumberFormatException if s is nonnull and
     * doesn't represent a valid integer
     */
    public static Integer parseInt(String s) {
        return (s == null) ? (Integer)null : Integer.parseInt(s);
    }
    public static void main(String[] args) {
        System.out.println(parseInt("-1"));
        System.out.println(parseInt(null));
        System.out.println(parseInt("1"));
    }
}


输出

-1
Exception in thread "main" java.lang.NullPointerException

解析

在(Integer)null : Integer.parseInt(s);这一行,前者(Integer)null,不会报空指针异常。
抛出异常是因为:前者是Integer类型,后者是int类型。  
根据三元表达式规则,这两个类型必须是一致的。因此前者需要拆箱。
拆箱需要调用的方法为:integer.intValue();这里null.intValue()。因此报空指针异常

总结
三元表达式的规则:冒号前后表达式或变量的数据类型必须一致。


引用
三元表达式转换规则

相关文章

网友评论

      本文标题:java三元表达式转换规则

      本文链接:https://www.haomeiwen.com/subject/xiinrctx.html