Convert char Array to String
This page was last reviewed on Nov 9, 2023.
Dot Net Perls
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.
char Array
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.
Note With one argument, the String constructor uses all characters in the array to create a String.
Here The constructor creates a 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.
String toCharArray
Here We invoke 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); } }
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.
Chars are two bytes. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 9, 2023 (edit).
© 2007-2024 Sam Allen.