为什么这段代码没有抛出nullPointerException?

代码片段如下。

我知道 String 的默认值是null并且它被分配给str. 我不明白的是为什么null在第一种情况下打印而不在其他情况下打印(如第二个代码片段)。

public class Case1{

    static String str;

    public static void main(String[] args){

        System.out.println(str);
    }
}

Code prints 'null' without quotes
public class Case2{

    public static void main(String[] args){

        String a[][] = { {}, null };
        System.out.println(a[1][0]);
    }
}

Code throws nullPointerException

任何解释将不胜感激。

回答

在您的第二个示例中,您正在做的是访问不存在数组的第一个值:

String a[][] = { {}, null };

所以 a[1] 是空值,并且没有该空值的 [0]。


以上是为什么这段代码没有抛出nullPointerException?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>