Java Program to Convert Byte Array to String
There are multiple ways to change byte array to String in Java, you can either use methods from JDK, or you can use open-source complementary APIs like Apache commons and Google Guava. These APIs provide at least two sets of methods to create a String from byte array; one, which uses default platform encoding, and the other which takes character encoding.
It’s also one of the best practices specifying character encoding while converting bytes to the character in any programming language. It might be possible that your byte array contains non-printable ASCII characters. Let’s first see JDK’s way of converting byte to a string. Some programmers, also recommend using Charset over String for specifying character encoding, e.g. instead of “UTF-8” use StandardCharsets.UTF_8 mainly to avoid Unsupported Encoding Exception in the worst case.
Case 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. It is as shown in the below example which is as follows:
[71, 101, 101, 107, 115, 102, 111, 114, 103, 101, 101, 107, 115] Geeksforgeeks
Case 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.
Note: Here we are using StandardCharsets.UTF_8 to specify the encoding. Before Java 7, we can use the Charset. for Name(“UTF-8”).
That’s all about converting a byte array to Java String.
Conclusion: We should focus on the type of input data when working with conversion between byte array and String in Java.
- Use String class when you input data is string or text content.
- Use Base64 class when you input data in a byte array.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.