Today we will learn how to convert String to a char array and then char array to String in Java.
String to char array
Java String is a stream of characters. String class provides a utility method to convert String to a char array in java. Let’s look at this with a simple program.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.journaldev.util; import java.util.Arrays; public class StringToCharArray { public static void main(String[] args) { String str = "journaldev.com"; char[] charArr = str.toCharArray(); // print the char[] elements System.out.println("String converted to char array: " + Arrays.toString(charArr)); } } |
Below image shows the output produced by the above program.
String.toCharArray
internally use System class arraycopy
method. You can see that from below method implementation.
1 2 3 4 5 6 7 |
public char[] toCharArray() { char result[] = new char[value.length]; System.arraycopy(value, 0, result, 0, value.length); return result; } |
Notice the use of Arrays.toString
method to print the char array. Arrays
is a utility class in java that provides many useful methods to work with array. For example, we can use Arrays class to search, sort and java copy array operations.
char array to String
Let’s look at a simple program to convert char array to String in Java.
1 2 3 4 5 6 7 8 9 10 |
package com.journaldev.util; public class CharArrayToString { public static void main(String[] args) { char[] charArray = {'P','A','N','K','A','J'}; String str = new String(charArray); System.out.println(str); } } |
Below image shows the output produced by char array to String program.
We are using String class constructor that takes char array as an argument to create a String from a char array. However if you look at this constructor implementation, it’s using Arrays.copyOf
method internally.
1 2 3 4 5 |
public String(char value[]) { this.value = Arrays.copyOf(value, value.length); } |
Again Arrays.copyOf
method internally use System.arraycopy
native method.
1 2 3 4 5 6 7 8 |
public static char[] copyOf(char[] original, int newLength) { char[] copy = new char[newLength]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } |
So we can clearly see that System arraycopy() is the method being used in both Strings to char array and char array to String operations. That’s all for converting String to char array and char array to String example program.
Reference: toCharArray API Doc