繁体   English   中英

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

[英]Why is this code not throwing a 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] 是 null 值,并且没有那个 null 的 [0]。

在您的示例中,您尝试访问 null 上的值。

看下面的代码

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

它会打印

null

当您尝试访问 null 上的第 0 个元素时,它会抛出空指针预期,因为您尝试访问null上的元素

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

它将 output

Exception in thread "main" java.lang.NullPointerException

在 case1 中,您只是打印字符串并且没有为其分配任何值,因此默认情况下会打印 null。 您无需对该字符串执行任何操作以在此处引发 NullPointerException。 因此它不会抛出任何异常。

在 case2 中,您将 null 值分配给字符串数组并尝试使用索引获取 null object。 因此你得到了 nullPointerException。

如果您使用以下代码更改 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 打印不带引号的“null”

暂无
暂无

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

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