Convert a byte array to a String in Java
This post will discuss how to convert a byte array to string in Java.
We know that a string store textual data in Java, and byte[]
stores binary data, so we should avoid conversion between them. Nevertheless, we might find ourselves in situations where we have no choice. This post covers how to convert a byte array to string in Java, with and without specifying character encoding.
1. Without character encoding
We can convert the byte
array to String for the ASCII character set without even specifying the character encoding. The idea is to pass the byte[]
to the String constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.io.IOException; import java.util.Arrays; // Convert a byte array to string in Java class Main { public static void main(String[] args) throws IOException { byte[] bytes = "Techie Delight".getBytes(); // System.out.println(Arrays.toString(bytes)); // Create a string from the byte array without specifying // character encoding String string = new String(bytes); System.out.println(string); } } |
Output:
Techie Delight
2. With character encoding
We know that a byte
holds 8 bits, which can have up to 256 distinct values. This works fine for the ASCII character set, where only the first 7 bits are used. For character sets with more than 256 values, we should explicitly specify the encoding, which tells how to encode characters into sequences of bytes.
In the following program, we have used StandardCharsets.UTF_8
to specify the encoding. Before Java 7, we can use the Charset.forName("UTF-8")
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.io.IOException; import java.nio.charset.StandardCharsets; // Convert a byte array to string in Java class Main { public static void main(String[] args) throws IOException { byte[] bytes = "Techie Delight".getBytes(StandardCharsets.UTF_8); // Create a string from the byte array with "UTF-8" encoding String string = new String(bytes, StandardCharsets.UTF_8); System.out.println(string); } } |
Output:
Techie Delight
That’s all about converting a byte array to Java String.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)