Convert between String and Char Array in Java

Convert a String to an Array of Characters

The String.toCharArray() method converts a string to a new character array.

String str = "abcde";
char[] arr = str.toCharArray();
for (char c : arr)
    System.out.println(c);

The following code gets an array of Character objects, instead of a character array.

String str = "abcde";
Character[] arr = new Characer[str.length()];
for (int i = 0; i < str.length(); i++)
    arr[i] = str.charAt(i);

Convert an Array of Characters to a String

A string can be directly created from a character array.

char[] arr = {'a', 'b', 'c', 'd', 'e'};
String str = new String(arr);
System.out.println(str);

From an array of Character objects, we can first convert it to a character array.

Character[] cs = {'a', 'b', 'c', 'd', 'e'};
char arr = new char[cs.length];
for (int i = 0; i < cs.length; i++)
    arr[i] = cs[i];
String str = new String(arr);

Comments

comments