Convert a string to a new character array.
The toCharArray() method converts this string to a new character array. The length of the returned array equals the length of the string, and each element corresponds to the character at the same index.
This method allocates a new array each time it is called. The returned array is independent of the original string, so modifications to the array do not affect the string and vice versa.
This is commonly used when you need to manipulate individual characters, sort characters, or pass string data to methods that require char arrays. It is also useful for algorithms that need random access to characters with index-based modification.
char[] chars = "Hello".toCharArray();
// chars = ['H', 'e', 'l', 'l', 'o']
chars[0] = 'J';
// chars = ['J', 'e', 'l', 'l', 'o']