为什么在这种情况下它不会抛出NullPointerException

Paw*_*wan 3 java

我编写了我的应用程序,我遇到了一个要求,我需要将String转换为char数组I.

String str_a = "Testing";

char c[] = str_a.toCharArray(); 

for (char d : c) {
    System.out.println(d);
}
Run Code Online (Sandbox Code Playgroud)

因为我没有初始化 char c[]

我的问题是为什么它不抛出NullPointerException,通常这应该这样做

char[] char_array = new char[str_a.length()];

char_array = str_a.toCharArray();       

for (char d : c) {
    System.out.println(d);
}
Run Code Online (Sandbox Code Playgroud)

Pab*_*ruz 5

因为str_a.toCharArray();已经初始化并分配了一个合适的字符数组.此方法返回的内容已经为您进行了分配和初始化.