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

m0t*_*way 2 java arrays string nullpointerexception

实践测试中出现了这个问题:创建一个新的字符串数组,将其初始化为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");
        }
    }
Run Code Online (Sandbox Code Playgroud)

谢谢!

Eng*_*uad 14

因为你arr提到了null,所以它扔了一个NullPointerException.


编辑:

让我通过数字解释一下:

在此之后:

String arr[] = new String[10];
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

在此之后:

arr = null;
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

所以当你拨打这一行时:

arr[0] = "one";
Run Code Online (Sandbox Code Playgroud)

A NullPointerException将被抛出.

  • 漂亮的照片!+1 (2认同)