C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
One argument: With one argument, the String constructor uses all characters in the array to create a String.
Two arguments: Here the constructor creates a String starting at the first index and continuing for a certain number of chars (a count).
Java program that converts char array, String
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);
}
}
Output
Welcome!
Welcome
come
Here: We invoke toCharArray on a String and display the characters in the resulting array. We then convert back into a String.
Round-trip: In computer software, a round-trip method returns the converted data to its original state.
Java program that uses toCharArray
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);
}
}
Output
HERO
H
E
R
O
HERO