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.

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

Download  Run Code

Output:

Techie Delight

That’s all about converting a byte array to Java String.