Java String Handling

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 constructor of the String class. Example also shows how to decode byte array to String using UTF-8 character set.

How to convert byte array to String?

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

This constructor decodes the specified byte array using 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 platform’s default character set, behavior of this constructor is unspecified. Please also note that, 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, String constructor decodes the byte array using 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 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 byte 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,

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

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.