Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why it doesn't throw a NullPointerException in this case

Tags:

java

I am coding for my Applictation , i came across a requirement , where i needed to convert a String to char array I

String str_a = "Testing";

char c[] = str_a.toCharArray(); 

for (char d : c) {
    System.out.println(d);
}

As i did not initialize the char c[]

My question is why it doesn't throw a NullPointerException, typically this should be done this way

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

char_array = str_a.toCharArray();       

for (char d : c) {
    System.out.println(d);
}
like image 293
Pawan Avatar asked May 09 '26 08:05

Pawan


1 Answers

Because str_a.toCharArray(); already initializes and allocates a proper character array. What this method is returning already did the allocation and initialization for you.

like image 108
Pablo Santa Cruz Avatar answered May 11 '26 20:05

Pablo Santa Cruz