String s = null; System.out.println(s);
 请问:为什么这样不会报错,而是输出null。 
不是会调用null的toString方法吗,不会报空指针的错误吗?null

解决方案 »

  1.   

    没有调用toString方法,楼主可以试试String s = null; System.out.println(s.toString());就明白了
      

  2.   


    String str = null;
    System.out.println(str.toString());Exception in thread "main" java.lang.NullPointerException
    如果调用toString()方法会报异常System.out.println(str);这个没有调用toString方法。
      

  3.   

    public class Str {
        public static void main(String []args) {
            String str = null;
            System.out.println(str);
            System.out.println(str.toString());
        }}console:
    null
    Exception in thread "main" java.lang.NullPointerException
    at Str.main(Str.java:6)为什么会是这样的结果,这个你要问设计JDK的人员。源代码中的代码如下:public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
        }
    public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
        }当传入的字符串==null时,打印null。
    所以不会出错报null指针异常。只有在转换的时候会报。
      

  4.   

    学java的有必要去看JDK源代码吗
      

  5.   

    没有报异常是因为jdk里print,println方法对参数的处理。楼上有讲解。
      

  6.   

    .toString()。
    这样就会报错了。