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.
1 |
public String(byte[] bytes) |
This constructor decodes the specified byte array using the default character set of the platform and returns the String object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.javacodeexamples.stringexamples; public class ByteArrayToStringExample { public static void main(String[] args) { //byte array byte[] byteArray = new byte[]{74, 97, 118, 97}; /* * Convert byte array to String * using constructor of the String class */ String str = new String(byteArray); //print the string System.out.println("String from byte array: " + str); } } |
Output
1 |
String from byte array: Java |
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.
1 |
public String(byte[] bytes, Charset charset) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.javacodeexamples.stringexamples; import java.nio.charset.Charset; public class ByteArrayToStringExample { public static void main(String[] args) { //byte array byte[] byteArray = new byte[]{74, 97, 118, 97}; String str = new String(byteArray, Charset.forName("UTF-8")); //print the string System.out.println("decode byte array to string using UTF-8: " + str); } } |
Output
1 |
decode byte array to string using UTF-8: Java |
If you are using Java 7 or later version, you can use,
1 |
String str = new String(byteArray, StandardCharsets.UTF_8 ); |
instead of,
1 |
String str = new String(byteArray, Charset.forName("UTF-8")); |
This example is a part of the Java String tutorial.
Please let me know your views in the comments section below.