How to convert String to char[] array and char[] array to String in Java?

UPDATED: 09 February 2015
String to char array in Java

One of the rare question asked in Java interview however its worth knowing the basics of String.

Source Code
public class StringCharArray {
    public static void main(String[] args) {
        String str = "javaQuery";
        
        /* Conver String to char[] array */
        char[] charArray = str.toCharArray();
        
        /* Print the char[] array */
        System.out.println("String to char[]:");
        for(char ch : charArray){
            System.out.println(ch);
        }
        
        /* Convert char[] array to String */
        String strFromCharArray = String.valueOf(charArray);
        
        System.out.println("------------------------");
        
        /* Print the String */
        System.out.println("char[] to String: "+strFromCharArray);
    }
}

Output
String to char[]:
j
a
v
a
Q
u
e
r
y
------------------------
char[] to String: javaQuery

0 comments :