Convert a String to Character Array in Java
Converting a string to a character array is a common operation in Java. We convert string to char array in Java mostly for string manipulation, iteration, or other processing of characters. In this article, we will learn various ways to convert a string into a character array in Java with examples.
Example:
The toCharArray()
method is the simplest and most efficient way to convert a string to a character array.
// Java Program to Convert a String to a Character Array
// using toCharArray()
import java.util.Arrays;
public class StringToCharArray {
public static void main(String[] args) {
// Defining a string
String s = "Java";
// Converting the string to a character array
char[] c = s.toCharArray();
System.out.println("" + Arrays.toString(c));
}
}
Output
[J, a, v, a]
Note: We can use the charAt() method, that returns the character at the specified index of a string., where the index is zero-based.
Other Ways to Convert a String to Character Array
Using Streams (Java 8+)
Java Streams provide a functional way to convert a string into characters and process them for modern Java applications.
// Java Program to Convert String to Character Array
// Using Streams
import java.util.Arrays;
public class StringToCharArray {
public static void main(String[] args) {
// Defining a string
String s = "Java";
// Converting string to character array using streams
char[] ch = s.chars()
.mapToObj(c -> (char) c)
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString()
.toCharArray(); // Convert StringBuilder to char array
System.out.println(Arrays.toString(ch));
}
}
Output
[J, a, v, a]
Explanation:
s.chars()
: This converts the string into anIntStream
of character codes.mapToObj(c -> (char) c)
: This maps each integer character code to aCharacter
object.collect(...)
: It collects the characters into aStringBuilder
.toString().toCharArray()
: It converts theStringBuilder
to a string, then to achar[]
array.
Using String.split()
This is not an efficient way to convert string to character array. But we
can split the string into individual characters using the split()
method.
Example:
// Java Program to Convert String to Character Array
// Using split()
import java.util.Arrays;
public class StringToCharArray {
public static void main(String[] args) {
// Defining a string
String s = "Java";
// Splitting the string into individual characters
String[] ch = s.split("");
System.out.println("" + Arrays.toString(ch));
}
}
Output
[J, a, v, a]
When to Use Which Method
- toCharArray(): For simplicity and efficient way.
- Streams: For modern functional programming.
- split(): Not an efficient way, do not prefer to use.