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 the Author

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

Comments

Leave a Reply

avatar
newest oldest most voted
Michael
Guest
Michael

Really useful…Thanks

Antuan Sanders
Guest
Antuan Sanders

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

praneeth
Guest
praneeth

Can you help me in this pls

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

lakshyaveer
Guest
lakshyaveer

atleast we have to use toCharArray method.

LedZelkin
Guest
LedZelkin

This Website is really amazing.

Thx for your work