In this post, we will discuss how to convert a byte array to String in Java.
We know that a String stores textual data in Java, and byte[] stores binary data, so conversion between the two should be avoided. 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
For ASCII character set, we can convert the byte array to String 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 Util { 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 ASCII character set, where only the first 7 bits is 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 below program, we have used StandardCharsets.UTF_8 to specify the encoding. Before Java 7, we can use 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 Util { 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
Thanks for reading.
Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
Leave a Reply
Nice