String to char array, char array to String in Java

Filed Under: Java

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.


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 to char array in java

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


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.


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.

char array to string in java

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.


public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }

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


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.

You can checkout more array examples from our GitHub Repository.

Reference: toCharArray API Doc

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages