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


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


Techie Delight


1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


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

newest oldest most voted
Notify of