The char[]
(a character array) and String
are very similar as they both store a sequence of characters. Although the String class is more extensive (has a ton of functions for manipulating sequence), it is sometimes necessary to convert a String into a character array.
For example, if a function accepts a parameter as char[]
, we cannot pass a String to it; so, instead of declaring a char[]
of size equal to the string’s length and copying every character one by one into it, we can use toCharArray()
makes the task easier.
This function is present in the String class; it returns a char[]
populated with the character sequence of the string. The size of this array is equal to the string’s length.
class Main{public static void main(String[] args){String str = "Hello world!";char[] arr = str.toCharArray();for(int i = 0; i < arr.length; i++)System.out.print(arr[i]);System.out.println("\nSize of char[] = " + arr.length);}}
Free Resources