How to convert a string to a char array in Java

Java provides several ways to convert a string into an array of characters (char[]). You can use the String.toCharArray() or String.chars() method to convert a string into a characters array.

Convert a string to a char[] using String.toCharArray()

The String.toCharArray() method returns an array of characters from the given string. The returned character array has the same length as the length of the string.

Here is an example:

// Declare a string
String str = "Java Protips";

// Convert string to a char array
char[] chars = str.toCharArray();

System.out.println(Arrays.toString(chars));
// [J, a, v, a,  , P, r, o, t, i, p, s]

Convert a string to a char[] using String.chars()

The String.chars() is yet another simple method to transform a string into an array of characters in Java 8 and higher, as shown below:

// Declare a string
String str = "Java Protips";

// Convert string to a char array
Character[] chars = str.chars()
        .mapToObj(c -> (char) c)
        .toArray(Character[]::new);

System.out.println(Arrays.toString(chars));
// [J, a, v, a,  , P, r, o, t, i, p, s]

Read this article if you want to convert a character array to a string in Java.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.