How to convert byte array to String in Java
The process of converting a byte array to a String is called decoding. This process requires a Charset. Though, we should use charset for decoding a byte array.
There are two ways to convert byte array to String:
By using String Class Constructor
The simplest way to convert a byte array into String, we can use String class constructor with byte as the constructor argument.
The following example does not use any character encoding.
By using UTF-8 encoding
Remember the character encoding while converting the byte array to String. Since bytes is the binary data while String is character data. It is important to know the original encoding of the text from which the byte array has created. When we use a different character encoding, we do not get the original string back.
Suppose, we have to read byte array from a file which is encoded in "ISO_8859_1". We do not have any character encoding while converting byte array to string. We convert byte array into String by using String class constructor, but it does not provide a guarantee that we will get the same text back. It is because the constructor of String class uses the platform's default encoding.
Bytes holds 8 bits which can have up to 256 distinct values. It works for ASCII character set, where only seven bits are used. If the character sets have more than 256 values, we should explicitly specify the encoding which tells how to encode characters into a sequence of bytes.
There are follllowing charsets supported by Java platform are:
When we do not remember exact encoding, in such cases our platform is not able to convert those special characters properly. This problem is solved by providing "UTF-8" as a character encoding. Java provides another overloaded constructor in String class which accepts character encoding.
In the following example, we have used StandardCharset.UTF_8 to specify the encoding.
In the following example, We have taken char while creating the byte array. It works because of autoboxing. The char 'T' is being converted to 84 in the byte array and so on. That's why the output of both byte array is the same.
The String class also has a constructor in which we can pass byte array and Charset as an argument. So the following statement can also be used to convert byte array to String in Java.
The String class also has a constructor to convert a subset of the byte array to String.
Let's see another example in which different encoding is used.