Why doesn't it throw NullPointerException in this case
I am coding my application, I ran into a requirement where I needed to convert a String array to a char array I
String str_a = "Testing";
char c[] = str_a.toCharArray();
for (char d : c) {
System.out.println(d);
}
Since I have not initialized char c[]
My question is why it doesn't throw NullPointerException
, generally it 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);
}
source to share
Source Code toCharArray()
:
/**
* Converts this string to a new character array.
*
* @return a newly allocated character array whose length is the length
* of this string and whose contents are initialized to contain
* the character sequence represented by this string.
*/
public char[] toCharArray() {
char result[] = new char[count]; // <-- Here is the initialization :)
getChars(0, count, result, 0);
return result;
}
source to share
There is no need to initialize char_array
when you immediately assign the result str_a.toCharArray()
to char_array
.
In your second example, you are creating an empty array that is discarded immediately because you then compute str_a.toCharArray()
. The method toCharArray
calculates the value of the array and returns it, so you don't have to create it yourself.
source to share
Both methods work fine. The first defines the new array as a char array, and the second creates an empty array and sets it equal to the char array; when you go to it both are the same, and the second just has more lines.
You can also save time and do:
for(char c : str_a.toCharArray()){
System.out.println(c);
}
The method string.toCharArray()
returns a new one char[]
, you don't need to initialize this variable first.
Infact if you left your code as ...
char[] char_array = new char[str_a.length()];
char_array = str_a.toCharArray();
This initializes a variable for one instance char[]
and then removes that instance on the very next line. It's inefficient, pointless and confusing.
source to share