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);
}

      

+3


source to share


6 answers


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;
}

      

+3


source


Because it str_a.toCharArray();

already initializes and allocates the correct array of characters. What this method returns has already done the allocation and initialization for you.



+5


source


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.

+1


source


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);
}

      

+1


source


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.

0


source


as shown in the code, you are using the variable c, but instead of c you must use char_arra

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

char_array = str_a.toCharArray();       

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

      

0


source







All Articles