Convert String to a char array in Java

In this post, we will see how to convert String to a char array in Java.


 

1. Naive –

Naive solution would be to use a regular for loop to read all characters of the string and assign it to a char array one by one. This approach is very effective for smaller strings.

Java

Download   Run Code

Output:

[J, a, v, a]

2. String.toCharArray() –

We can convert string to a char array using String.toCharArray() function as shown below:

Java

Download   Run Code

Output:

[J, a, v, a]

3. Reflection

For long strings, nothing beats Reflection in terms of Performance. We can inspect any string using Reflection and access the backing array of specified string.

Java

Download   Run Code

Output:

[J, a, v, a]

 
Related Post: Iterate over Characters of the String in Java

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz