strange java string array null pointer exception [duplicate]

荒凉一梦 提交于 2020-01-02 21:13:33

问题


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!


回答1:


Because you made arr referring to null, so it threw a NullPointerException.


EDIT:

Let me explain it via figures:

After this line:

String arr[] = new String[10];

10 places will be reserved in the heap for the array arr:

and after this line:

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 will be thrown.




回答2:


With arr = null; you are deleting the reference to the object. So you can't access it anymore with arr[anynumber] .




回答3:


arr is null, and then... if it did print one, wouldn't you be surprised? put a string into a null?



来源:https://stackoverflow.com/questions/8089798/strange-java-string-array-null-pointer-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!