How to Convert a String to a Char Array in Java

A String variable in Java contains a collection of characters and is used for storing text. On the other hand, a variable of type Char is used for storing a single character. In this article, I will show you the easiest way to convert a String to a Char array in Java.

String to Char Array in Java

Here is an example that will allow you to easily convert a String to a Char array in Java.

public class ConvertStringToCharArray {

	public static void main(String[] args) {
		String sampleString = "convert me to char";
		char[] charArray = sampleString.toCharArray();
 
		for (char ch : charArray) {
			System.out.println(ch);
		}
	}
}

How we are converting a String to a Char array:

  • First, we define a String variable named “sampleString” that contains this text – “convert me to char”.
  • Now we use the built-in toCharArray function to convert “sampleString” to a Char array. This value is stored into a new Char array defined as “charArray”.
  • We use a “For” loop to loop through each element of this “charArray” as “ch” and print the output on the screen.

This is how the output will look like:

c
o
n
v
e
r
t

m
e

t
o

c
h
a
r
Disclosure: This page may contain affiliate links. If you follow one of those affiliate links and purchase something it will provide me with a little bit of a commission. This costs you nothing extra but helps maintain my site, free plugins, and themes. So I thank you for your support.

Leave a Comment