Convert a Byte Array to String in Java

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.

 

Download   Run Code

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").

 

Download   Run Code

Output:

Techie Delight

 

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Leave a Reply

avatar
  Subscribe  
Notify of