奇怪的java字符串数组空指针异常 [英] strange java string array null pointer exception
问题描述
这个问题在实践中检验想出了:创建一个新的字符串数组,初始化为null,则初始化第一个元素,并打印出来。为什么这会导致空指针异常?为什么它不打印一?难道是与字符串不变性?
This problem came up in a practice test: create a new string array, initialize it to null, then initializing the first element and printing it. Why does this result in a null pointer exception? Why doesn't it print "one"? Is it something to do with string immutability?
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");
}
}
谢谢!
推荐答案
由于你发改编
参考空
,所以它扔了 NullPointerException异常
。
Because you made arr
referring to null
, so it threw a NullPointerException
.
结果
编辑:
让我通过数据解释一下:
Let me explain it via figures:
这行之后:
String arr[] = new String[10];
10个名额将在堆阵改编
保留:
这行之后:
arr = null;
您删除的参考阵列,使其参考空
:
You are removing the reference to the array and make it refer to null
:
所以,当你调用这个行:
So when you call this line:
arr[0] = "one";
A NullPointerException异常
将被抛出。
这篇关于奇怪的java字符串数组空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!