Skip to content

Java convert String to character array Example

This Java example shows how to convert string to character array (char array) in Java as well as how to convert char array to string in Java.

How to convert string to char array in Java?

Use the toCharArray method of the String class to convert the string object to char array.

This method creates a new character array whose length is equal to the length of the string object containing the character sequence.

Output

How to convert string to Character object array in Java?

There is no direct method to convert a string to a Character object array in Java. Below given are two possible solutions.

a) Using for loop

Basically we have created a Character array whose length is equal to the length of the string and populated it one character at a time using the for loop.

b) Using Apache Commons lang library

If you have the Apache Commons lang library, you can use the toObject method of the ArrayUtils class to convert primitive char array to Character object array as given below.

This method converts an array of primitive char to array of Character wrapper objects.

How to convert a char array to a string?

Use a String constructor that accepts a char array as an argument and returns a string representation of character sequence.

This constructor creates and returns a new string object containing a sequence of characters contained in the char array.

Output

This example is a part of the Java String tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.