How to Create String from Char Array in Java
In Java, you can create a
String from a char array by passing the array to the String constructor like new String(charArray). This converts the array of characters into a readable string.Syntax
The basic syntax to create a String from a char array is:
new String(charArray): Creates a new string containing all characters from the array.new String(charArray, offset, count): Creates a string from a subset of the array starting atoffsetand usingcountcharacters.
java
char[] charArray = {'H', 'e', 'l', 'l', 'o'}; String str = new String(charArray); char[] charArray2 = {'J', 'a', 'v', 'a', ' ', 'R', 'o', 'c', 'k', 's'}; String str2 = new String(charArray2, 5, 5);
Example
This example shows how to convert a full char array and a part of a char array into strings and print them.
java
public class CharArrayToString { public static void main(String[] args) { char[] fullArray = {'H', 'e', 'l', 'l', 'o'}; String fullString = new String(fullArray); System.out.println(fullString); // Prints: Hello char[] partialArray = {'J', 'a', 'v', 'a', ' ', 'R', 'o', 'c', 'k', 's'}; String partialString = new String(partialArray, 5, 5); System.out.println(partialString); // Prints: Rocks } }
Output
Hello
Rocks
Common Pitfalls
Common mistakes include:
- Passing
nullinstead of a valid char array, which causes aNullPointerException. - Using incorrect
offsetorcountvalues that are out of bounds, causingStringIndexOutOfBoundsException. - Trying to assign a char array directly to a String variable without using the constructor, which is not allowed.
java
char[] chars = {'a', 'b', 'c'}; // Wrong: This will cause a compile error // String wrongString = chars; // Correct: String correctString = new String(chars); // Wrong: Using invalid offset and count // String errorString = new String(chars, 2, 5); // Throws exception
Quick Reference
Remember these key points when creating strings from char arrays:
- Use
new String(charArray)for the whole array. - Use
new String(charArray, offset, count)for a part of the array. - Check array bounds to avoid exceptions.
Key Takeaways
Use the String constructor with a char array to create a string: new String(charArray).
You can create a string from part of a char array using new String(charArray, offset, count).
Always ensure offset and count are within the array bounds to avoid errors.
You cannot assign a char array directly to a String variable without conversion.
Passing null as the char array will cause a NullPointerException.