奇怪的java字符串数组空指针异常
这个问题是在实践测试中出现的:创建一个新的字符串数组,将其初始化为空,然后初始化第一个元素并打印它。为什么会出现空指针异常呢?为什么它不打印“一”?这与字符串不变性有关吗?
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");
}
}
谢谢!
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");
}
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为您使
arr
引用了null
,所以它抛出了NullPointerException
。编辑:
让我用数字来解释一下:
在这一行之后:
堆中将为数组
arr
保留 10 个位置:并在此行之后:
您将删除对数组的引用并使其引用
null
:因此,当您调用此行时:
将抛出
NullPointerException
。Because you made
arr
referring tonull
, so it threw aNullPointerException
.EDIT:
Let me explain it via figures:
After this line:
10 places will be reserved in the heap for the array
arr
:and after this line:
You are removing the reference to the array and make it refer to
null
:So when you call this line:
A
NullPointerException
will be thrown.使用
arr = null;
,您将删除对该对象的引用。因此您无法再使用
arr[anynumber]
访问它。With
arr = null;
you are deleting the reference to the object.So you can't access it anymore with
arr[anynumber]
.arr is null
,然后...如果它确实打印了one
,您不会感到惊讶吗?将字符串放入空值中?arr is null
, and then... if it did printone
, wouldn't you be surprised? put a string into a null?