Convert a string to a char array in Java
This post will discuss how to convert a string to a char array in Java.
There are several ways to convert a string to a char array in Java, which is the process of splitting the sequence of characters in the string into individual characters and storing them in an array. Some of the possible methods are:
1. Using String.toCharArray() method
A simple and most common way to convert a string to a char array in Java is using the String.toCharArray() method, which returns a new char array that contains the same characters as the string. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.Arrays; class Main { public static void main(String[] args) { String s = "Java"; char[] chars = s.toCharArray(); System.out.print(Arrays.toString(chars)); // [J, a, v, a] } } |
2. Using a loop
Another option is to use a for loop to iterate over the characters of the string and assign them to a new char array. This method requires us to create a new char array with the same length as the string and use the String.charAt() method to access each character of the string by its index. This approach can be used for the smaller strings. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.Arrays; class Main { public static void main(String[] args) { String s = "Java"; char[] chars = new char[s.length()]; for (int i = 0; i < s.length(); i++) { chars[i] = s.charAt(i); } System.out.print(Arrays.toString(chars)); // [J, a, v, a] } } |
3. Using Reflection
A third way to convert a string to a char array in Java is using Reflection. For long strings, nothing beats reflection in terms of performance. We can inspect any string using reflection and access the backing array of the specified string. Here is an example of how to use reflection for this task:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.lang.reflect.Field; import java.util.Arrays; class Main { public static void main(String[] args) { String s = "Java"; Field field = null; try { field = String.class.getDeclaredField("value"); } catch (NoSuchFieldException e) { e.printStackTrace(); } field.setAccessible(true); char[] chars = new char[0]; try { chars = (char[]) field.get(s); } catch (IllegalAccessException e) { e.printStackTrace(); } System.out.print(Arrays.toString(chars)); // [J, a, v, a] } } |
Note that setAccessible() method is deprecated with Java 9 and will not work in the future. Therefore, the code would result in an illegal reflective access operation and throw java.lang.IllegalAccessException. That’s all about converting a string to a char array in Java.
Related Post:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)