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
Man I really love this site. So many clean snippets.
I see 2 package declaration. Is that correct?
package com.mkyong.utils;
package com.mkyong.pageview;
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?
This Website is really amazing.
Thx for your work
Really useful…Thanks
Can you help me in this pls
how to convert a string to char array with out using library functions
String testString = “test string”;
char[] charArray = new char[testString.length()];
for(int i=0; i< testString.length();i++){
charArray[i] = testString.charAt(i);
}
atleast we have to use toCharArray method.