Looking to convert Java Char array to String?
Lets explore numbers of ways to achieve it using Java programming language.
Char array can be converted to String and vice versa.
- Using String Constructor
- With StringBuilder
- Using String.valueOf() Method
- Using String.copyValueOf() Method
- Utilizing Java 8 Streams
- Using Google’s Guava Joiner Method
Allocate a String that exhibits the sequence of characters present in a char array.
As String is immutable in Java, the consecutive modification of the character array does not impact the allocated String.
Using String Constructor
The String class provides inbuilt constructor which accepts a char array as an argument.
public static void main(String[] args) {
try {
char[] charArray = { 'W', 'E', 'L', 'C', 'O', 'M', 'E'};
String value = new String(charArray);
System.out.println("String Class Value is: " +value);
} catch (Exception e) {
e.printStackTrace();
}
}
Output: String Class Value is: WELCOME
With StringBuilder
The following code demonstrates converting a char array to a String using StringBuilder.
public static void main(String[] args) {
try {
final char[][] arrayCharArray = {{'w','e'},{'l','c'},{'o','m','e'}};
StringBuilder sb = new StringBuilder();
for (char[] childArray : arrayCharArray) {
sb.append(childArray);
}
System.out.println("After Forming as String: " +sb);
} catch (Exception e) {
e.printStackTrace();
}
}
Output: After Forming as String: welcome
Using String.valueOf() Method
The String class provides the valueOf() method which converts a char array to a string directly.
public static void main(String[] args) {
try {
char[] charArray = { 'W', 'E', 'L', 'C', 'O', 'M', 'E'};
String value = String.valueOf(charArray);
System.out.println("String Value is: " +value);
} catch (Exception e) {
e.printStackTrace();
}
}
Output: String Value is: WELCOME
Using String.copyValueOf() Method
The String.copyValueOf() method copies a char array to a string in java.
public static void main(String[] args) {
try {
char[] charArray = { 'W', 'E', 'L', 'C', 'O', 'M', 'E'};
String value = String.copyValueOf(charArray);
System.out.println("String copyValueOf is: " +value);
} catch (Exception e) {
e.printStackTrace();
}
}
Output: String copyValueOf is: WELCOME
Utilizing Java 8 Streams
We can utilize the Collectors.joining() method to form a String using Java 8 Streams.
public static void main(String[] args) {
try {
Character[] charArray = { 'W', 'E', 'L', 'C', 'O', 'M', 'E'};
Stream charStream = Arrays.stream(charArray);
String value = charStream.map(String::valueOf).collect(Collectors.joining());
System.out.println("String Java 8 Stream is: " +value);
} catch (Exception e) {
e.printStackTrace();
}
}
Output: String Java 8 Stream is: WELCOME
Using Google’s Guava Joiner Method
We can use the Guava Common Base Joiner method to convert a Character array to a delimiter string value.
public static void main(String[] args) {
try {
Character[] charArray = { 'W', 'E', 'L', 'C', 'O', 'M', 'E'};
String value = Joiner.on("-").join(charArray);
System.out.println("Joiner Value is: " +value);
} catch (Exception e) {
e.printStackTrace();
}
}
Output: Joiner Value is: W-E-L-C-O-M-E
Convert a Byte Array to String in Java
As we know byte[] stores binary data and String stores text data.
So lets see how to convert a byte array to string with character encoding and without character encoding.
With Character Encoding:
It supports both UNICODE and ASCII format.
In this case, lets use StandardCharsets.UTF_8 to specify the type of character encoding type.
This tells how to encode the input characters into the sequence of bytes.
public static void main(String[] args) throws IOException
{
String value = "Byte Array";
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
// Now Create a string from a byte array with "UTF-8" encoding
String result = new String(bytes, StandardCharsets.UTF_8);
System.out.println(result);
}
Output:
Byte Array
Without Character Encoding:
Lets convert byte array to string without specifying the character encoding.
So here we declared an string variable and converted into bytes using getBytes() method.
Finally passed the bytes to String object instance to achieve the desired output.
public static void main(String[] args) throws IOException
{
String value = "Byte Array";
byte[] bytes = value.getBytes();
String result = new String(bytes);
System.out.println(result);
}
Output:
Byte Array
You May Also Love,
Iterate through the characters of a string in Java
Lets use for loop function to iterate the number of characters of a String.
Apply charAt() method to retrieve each character and check it.
public static void main(String[] args) throws IOException
{
String value = "char";
for (int i = 0; i < value.length(); i++){
char result = value.charAt(i);
System.out.println("printing : "+result);
}
}
Output:
printing : c
printing : h
printing : a
printing : r
Lets look at efficient way of using for loop function with below code snippet.
public static void main(String[] args) throws IOException
{
String value = "char";
for(char result : value.toCharArray()) {
System.out.println("printing : "+result);
}
}
Output:
printing : c
printing : h
printing : a
printing : r
Tip:
Unlike C, There’s no such entity as NULL in Java. Null is not a valid value for a char variable.
A char can have a integer value of zero, which has no particular significance.
To conclude this java tutorial, we covered various examples on converting char Array to a String in Java.
Frequently Asked Questions (FAQs)
What is the simplest way to convert a char array to a String in Java?
The simplest way is to use the String constructor, like this: new String(charArray).
How can I convert a char array to a String using StringBuilder in Java?
You can create a StringBuilder instance and append the char array to it, then convert it to a String.
Is there a method in Java to convert a char array to a String directly?
Yes, you can use String.valueOf(charArray) to convert it directly.
What are the advantages of using StringBuilder for char array to String conversion?
StringBuilder is efficient in terms of memory usage, especially when concatenating multiple strings or characters.
Can I use Java 8 Streams to convert a char array to a String?
Yes, Java 8 Streams can be used with Collectors.joining() to efficiently convert a char array to a String.
Is there a difference between String.valueOf(charArray) and String.copyValueOf(charArray)?
No, both methods are essentially the same and can be used interchangeably for converting a char array to a String.
How do I handle null or empty char arrays when converting to a String in Java?
You should check for null or empty arrays before conversion to avoid NullPointerException or to handle them as needed.
Can I use Google's Guava library for char array to String conversion?
Yes, Guava provides utilities like the Joiner class which can be used for this conversion, especially for joining with delimiters.
What are the common pitfalls to avoid while converting char array to String in Java?
Common pitfalls include not handling null arrays, inefficiently concatenating in loops, and character encoding issues.
Are there any thread-safety concerns with char array to String conversions in Java?
String conversions are generally thread-safe, but care should be taken if using shared mutable data structures like StringBuilder in a multithreaded context.