Char
array, String
Often we need Strings to pass to methods and use in Java programs. But sometimes, we have character data in an array—a char
array—and must convert it.
With the String
constructor, we can convert a char
array to a String
. We can convert even just a range of characters in the char
array. One or three arguments are needed.
Char
array to String
This program uses the String
constructor. It first creates and fills a char
array of 8 characters. It then converts char
ranges to Strings.
String
constructor uses all characters in the array to create a String
.String
starting at the first index and continuing for a certain number of chars (a count).public class Program { public static void main(String[] args) { // An example char array. char[] values = new char[8]; values[0] = 'W'; values[1] = 'e'; values[2] = 'l'; values[3] = 'c'; values[4] = 'o'; values[5] = 'm'; values[6] = 'e'; values[7] = '!'; // Create a string with the entire char array. String result = new String(values); System.out.println(result); // Use first 7 characters for a new String. String result2 = new String(values, 0, 7); System.out.println(result2); // Create a string with an offset. String result3 = new String(values, 3, 4); System.out.println(result3); } }Welcome! Welcome come
ToCharArray
The String
class
provides a useful toCharArray
method. This takes the characters in the string and places them in a new char
array.
toCharArray
on a String
and display the characters in the resulting array. We then convert back into a String
.public class Program { public static void main(String[] args) { // A string. String value = "HERO"; System.out.println(value); // Convert String to char array with toCharArray method. char[] result = value.toCharArray(); for(char element:result) { System.out.println(element); } // Round-trip our conversion. String roundTrip = new String(result); System.out.println(roundTrip); } }HERO H E R O HERO
For performance, I have found that avoiding String
creation is a good option. If you can redesign your methods to use char
arrays, you can often avoid many allocations.
In a char
array, we can manipulate these elements without forcing a String
allocation. This improves performance.
With char
arrays, we introduce extra complexity to our algorithms. But the benefits outweigh the costs. With the String
constructor and toCharArray
we convert back to Strings.