美文网首页
java中String的一个小陷阱

java中String的一个小陷阱

作者: 寇寇寇先森 | 来源:发表于2018-03-08 20:47 被阅读0次

    首先大家看一段代码

    public class HelloWorld {  
        public static void main(String args[]) {  
            String s = null;  
            s = s+"word";  
            System.out.println("hello " +s);  
        }  
    }  
    

    大家猜猜输出结果是什么?hello word吗?
    错了,答案是:hello nullword
    为什么会是这样的结果呢?
    这是因为:s = s+"word"; 等价于 s = String.valueOf(s)+"word"; Integer,Double都一样。
    分析一下String的源码可以得出答案:

    public static String valueOf(Object obj) {  
      return (obj == null) ? "null" : obj.toString();  
    }  
    

    String的valueof方法参数为obj的时候,如果obj为Null,会把null转为"null",所以会出这样的结果。

    相关文章

      网友评论

          本文标题:java中String的一个小陷阱

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