Here you will learn about different ways to convert string to character array in java.
1. Using String.toCharArray() Method
We can easily convert string to character array using String.toCharArray() method. It can be done in following way.
package com; public class StringToArray { public static void main(String...s){ String str = "I Love Java"; char charArray[]; //converting string to character array charArray = str.toCharArray(); for(char c : charArray){ System.out.print(c + " "); } } }
Output
I L o v e J a v a
2. Writing Own Logic
We can also writing our own logic. Each character of string is extracted using String.charAt() method and inserted into the character array.
package com; public class StringToArray { public static void main(String...s){ String str = "I love Java"; char charArray[] = new char[str.length()]; //converting string to character array for(int i = 0; i < str.length(); ++i){ charArray[i] = str.charAt(i); } for(char c : charArray){ System.out.print(c + " "); } } }
Please comment below if you know any other way to do this.