String.toCharArray() / String.copyValueOf()
Methods for converting a string to a character array (char[]), or for creating a string from a character array. Useful when you need to process a string character by character, or when combining with the Stream API.
Syntax
// Converts a string to a char array. string.toCharArray(); // Creates a string from a char array. String.copyValueOf(char[] data); String.copyValueOf(char[] data, int offset, int count); // Returns an IntStream of code points for each character in the string (Java 8 and later). string.chars();
Method List
| Method | Description |
|---|---|
| toCharArray() | Returns a new char[] whose elements are the characters of the string. |
| String.copyValueOf(char[] data) | Creates and returns a string from the entire character array. Equivalent to new String(char[]). |
| String.copyValueOf(char[] data, int offset, int count) | Creates and returns a string from count characters of the array starting at offset. |
| chars() | Returns an IntStream treating each character in the string as an int (code point). Available in Java 8 and later. |
Sample Code
// Convert a string to a char array using toCharArray().
String str = "Hello";
char[] chars = str.toCharArray();
for (char c : chars) {
System.out.print(c + " "); // Prints "H e l l o ".
}
System.out.println();
// Modify the char array, then convert it back to a string.
char[] arr = "banana".toCharArray();
arr[0] = 'B'; // Change the first character to uppercase.
String modified = new String(arr);
System.out.println(modified); // Prints "Banana".
// Create a string from a char array using String.copyValueOf().
char[] data = {'J', 'a', 'v', 'a'};
String result = String.copyValueOf(data);
System.out.println(result); // Prints "Java".
// Specify offset and count to extract a portion of the array.
String partial = String.copyValueOf(data, 0, 2);
System.out.println(partial); // Prints "Ja".
// Use chars() with the Stream API.
long count = "Hello World".chars()
.filter(c -> c == 'l')
.count();
System.out.println(count); // Prints "3".
Notes
toCharArray() converts a string into an array of char values. The returned array is a copy, so modifying its elements does not affect the original string (strings in Java are immutable). This is convenient when writing a loop to process a string one character at a time.
In Java 8 and later, chars() enables a more declarative style using the Stream API. Note that chars() returns a stream of int values (IntStream), not char values, so you must explicitly cast to (char) when treating the elements as characters.
To get the length of a string or retrieve a character at a specific position, use length() / charAt(). To extract a substring, use substring().
If you find any errors or copyright issues, please contact us.