Java How to Convert Char Array to String Easily
new String(charArray) or the method String.valueOf(charArray).Examples
How to Think About It
Algorithm
Code
public class CharArrayToString { public static void main(String[] args) { char[] chars = {'J', 'a', 'v', 'a'}; String str = new String(chars); System.out.println(str); } }
Dry Run
Let's trace the example char array ['J', 'a', 'v', 'a'] through the code
Input char array
chars = ['J', 'a', 'v', 'a']
Create string from char array
str = new String(chars) results in "Java"
Print the string
Output: Java
| Step | Action | Value |
|---|---|---|
| 1 | Input char array | ['J', 'a', 'v', 'a'] |
| 2 | Convert to String | "Java" |
| 3 | Print output | Java |
Why This Works
Step 1: Using String constructor
The new String(charArray) creates a new string by joining all characters in the array.
Step 2: Alternative method
The String.valueOf(charArray) method also converts the char array to a string in a similar way.
Step 3: Result
Both methods produce a string that contains all characters from the array in order.
Alternative Approaches
public class CharArrayToString { public static void main(String[] args) { char[] chars = {'H', 'i'}; String str = String.valueOf(chars); System.out.println(str); } }
public class CharArrayToString { public static void main(String[] args) { char[] chars = {'B', 'y', 'e'}; StringBuilder sb = new StringBuilder(); for (char c : chars) { sb.append(c); } System.out.println(sb.toString()); } }
Complexity: O(n) time, O(n) space
Time Complexity
Converting a char array to a string requires processing each character once, so it takes linear time proportional to the array length.
Space Complexity
A new string is created that stores all characters, so space used is proportional to the array size.
Which Approach is Fastest?
Using the String constructor or String.valueOf is equally efficient and simpler than manually appending characters.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String constructor | O(n) | O(n) | Simple direct conversion |
| String.valueOf() | O(n) | O(n) | Readable and concise code |
| StringBuilder append | O(n) | O(n) | Building string with modifications |
new String(charArray) for a quick and direct conversion from char array to string.