Java – How to convert String to Char Array

In Java, you can use String.toCharArray() to convert a String into a char array.

StringToCharArray.java

package com.mkyong.utils;

public class StringToCharArray {

    public static void main(String[] args) {

        String password = "password123";

        char[] passwordInCharArray = password.toCharArray();

        for (char temp : passwordInCharArray) {
            System.out.println(temp);
        }

    }

}

Output

p
a
s
s
w
o
r
d
1
2
3

Java 8 – Convert String to Stream Char

For Java 8, you can uses .chars() to get the IntStream, and convert it to Stream Char via .mapToObj


package com.mkyong.utils;
package com.mkyong.pageview;

public class Test {

    public static void main(String[] args) {

        String password = "password123";

        password.chars() //IntStream
                .mapToObj(x -> (char) x)//Stream<Character>
                .forEach(System.out::println);

    }

}

Output

p
a
s
s
w
o
r
d
1
2
3

References

  1. JavaDoc – toCharArray
  2. Why is String.chars() a stream of ints in Java 8?

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Antuan Sanders
11 years ago

Man I really love this site. So many clean snippets.

oiuyf
4 years ago

I see 2 package declaration. Is that correct?

package com.mkyong.utils;
package com.mkyong.pageview;

Randy
5 years ago

re: chars() method. I see it in Java 9 String class but not Java 8 String class, on the Oracle website.

Java 8: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

Java 9: https://docs.oracle.com/javase/9/docs/api/java/lang/String.html

Am I missing something?

LedZelkin
10 years ago

This Website is really amazing.

Thx for your work

Michael
11 years ago

Really useful…Thanks

praneeth
11 years ago

Can you help me in this pls

how to convert a string to char array with out using library functions

Girish
3 years ago
Reply to  praneeth

String testString = “test string”;
char[] charArray = new char[testString.length()];
for(int i=0; i< testString.length();i++){
charArray[i] = testString.charAt(i);
}

lakshyaveer
6 years ago
Reply to  praneeth

atleast we have to use toCharArray method.