gpt4 book ai didi

java - 奇怪的java字符串数组空指针异常

转载 作者:行者123 更新时间:2023-12-01 08:13:44 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What is a NullPointerException, and how do I fix it?

(12 个回答)


3年前关闭。




这个问题是在实践测试中出现的:创建一个新的字符串数组,将其初始化为null,然后初始化第一个元素并打印它。为什么这会导致空指针异常?为什么不打印“一个”?它与字符串不变性有关吗?

public static void main(String args[]) {
try {
String arr[] = new String[10];
arr = null;
arr[0] = "one";
System.out.print(arr[0]);
} catch(NullPointerException nex) {
System.out.print("null pointer exception");
} catch(Exception ex) {
System.out.print("exception");
}
}

谢谢!

最佳答案

因为你做了arrnull ,所以它抛出了 NullPointerException .

编辑:

让我通过数字来解释它:

在这一行之后:

String arr[] = new String[10];

将在堆中为数组保留 10 个位置 arr :

enter image description here

在这一行之后:
arr = null;

您正在删除对数组的引用并使其引用 null :

enter image description here

所以当你调用这条线时:
arr[0] = "one";

A NullPointerException将被抛出。

关于java - 奇怪的java字符串数组空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8089798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com