This example will show you how to use the java String class toCharArray() method to convert a Java String object to a character array.
1. How To Convert Java String Object To Character Array Example Source Code.
- ConvertStringToCharArray.java
public class ConvertStringToCharArray { public static void main(String[] args) { /* Declare and initiate the str object with assigned value. */ String str = "Java is a popular programming language."; /* Declare a char array without initial value. */ char charArr[]; /* Invoke toCharArray() method to convert str to char array. */ charArr = str.toCharArray(); /* Get char count in the array. */ int arrLen = charArr.length; /* Declare a Character object array. */ Character chaObjArr[] = new Character[arrLen]; /* Loop to print each char in the array in reverse order. */ for(int i=arrLen-1;i>=0;i--) { /* Get the char value at the specified index. */ char cha = charArr[i]; /* Print out the char. */ System.out.print(cha + " "); /* Cast the char to upper case Character object and save in chaObjArr. */ chaObjArr[i] = Character.toUpperCase(cha); } System.out.println(""); /* Loop in chaObjArr and print out each upper case character. */ for(int i=0;i<arrLen;i++) { /* Get each Character object. */ Character chaObj = chaObjArr[i]; /* Print it's data as String. */ System.out.print(chaObj.toString()); } } }
- Below is the output when you run the above java code.
. e g a u g n a l g n i m m a r g o r p r a l u p o p a s i a v a J JAVA IS A POPULAR PROGRAMMING LANGUAGE.