VOOZH about

URL: https://mkyong.com/java/convert-string-to-char-array-in-java/

⇱ Java - How to convert String to Char Array - Mkyong.com


Skip to content

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?

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Antuan Sanders
13 years ago

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

1
Reply
oiuyf
6 years ago

I see 2 package declaration. Is that correct?

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

0
Reply
Randy
7 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?

0
Reply
LedZelkin
12 years ago

This Website is really amazing.

Thx for your work

0
Reply
Michael
13 years ago

Really useful…Thanks

0
Reply
praneeth
14 years ago

Can you help me in this pls

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

-1
Reply
Girish
5 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);
}

0
Reply
lakshyaveer
8 years ago
Reply to  praneeth

atleast we have to use toCharArray method.

0
Reply