简体   繁体   English

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

[英]Why is this code not throwing a nullPointerException?

The code snippets are below.代码片段如下。

I understand that the default value for a String is null and this is assigned to str .我知道 String 的默认值为null ,它被分配给str What I don't understand is why null is printed in this first case but not in other cases (like the second code snippet).我不明白为什么在第一种情况下会打印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

Any explanation would be greatly appreciated.任何解释将不胜感激。

In your second example what you are doing is to access the first value of an nonexistent array:在您的第二个示例中,您正在做的是访问不存在的数组的第一个值:

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

So a[1] is the null value, and there is no [0] of that null.所以 a[1] 是 null 值,并且没有那个 null 的 [0]。

In your example you are trying to access value on the null.在您的示例中,您尝试访问 null 上的值。

Look at the following code看下面的代码

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

it will print它会打印

null

and when you try to access the 0th element on the null, it throw nullpointer expections because you are try to access a element on null当您尝试访问 null 上的第 0 个元素时,它会抛出空指针预期,因为您尝试访问null上的元素

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

it will output它将 output

Exception in thread "main" java.lang.NullPointerException

In case1, You are just printing string and no value is assigned there, So by default null is printed.在 case1 中,您只是打印字符串并且没有为其分配任何值,因此默认情况下会打印 null。 You do not perform any operation with that string to throw NullPointerException there.您无需对该字符串执行任何操作以在此处引发 NullPointerException。 Hence It doesn't throw any exceptions.因此它不会抛出任何异常。

In case2, You assign null value to string Array and tries to get with index so with null object.在 case2 中,您将 null 值分配给字符串数组并尝试使用索引获取 null object。 Hence you got nullPointerException.因此你得到了 nullPointerException。

if you change case2 with following code you will get null there too.如果您使用以下代码更改 case2,您也会在此处获得 null。

public class Case2{

public static void main(String[] args){

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

\Code prints 'null' without quotes \Code 打印不带引号的“null”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM