String to char array, char array to String in Java With Examples

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.

Below image shows the output produced by the above program.

string-to-char-array

String.toCharArray internally use System class arraycopy method. You can see that from below method implementation.

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.

Below image shows the output produced by char array to String program.

string-to-char-array

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.

Again Arrays.copyOf method internally use System.arraycopy native method.

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

By admin

Leave a Reply