Skip to content

Convert byte array to String in Java example

Convert byte array to String in Java example shows how to convert byte array to String using the constructor of the String class and UTF-8 character set.

How to convert byte array to string?

You can use a String constructor that accepts the byte array argument to convert the byte array to the string.

This constructor decodes the specified byte array using the default character set of the platform and returns the String object.

Output

Important Note:

If the bytes contained in the byte array cannot be decoded using the platform’s default character set, the behavior of this constructor is unspecified. Please also note that the string’s length may not be equal to the size of an array depending upon the character set used to encode the byte array.

How to decode UTF-8 byte array to String?

As given in the above example, the string constructor decodes the byte array using the default character set of the platform. It may produce undesirable results if the bytes are not valid for the default character set. Use String constructor which accepts a character set parameter while converting byte array to String to avoid that.

This constructor decodes the byte array to string using the character set specified. The length of the string may not be equal to the size of the array depending upon the character set specified. Additionally, this constructor replaces malformed characters and characters which cannot be mapped in the target character set with the default replacement string.

Output

If you are using Java 7 or later version, you can use,

instead of,

This example is a part of the Java String tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.