How to convert byte array to String

In this post, we will discuss various methods to convert byte array to String.

String(byte[])

This String constructor variant constructs a new String by decoding the bytes array using the default charset.

byte[] byteArray = {'a','b','c','d','e'};
String str1 = new String(byteArray);
System.out.println(str1);

String(byte[], Charset)

This String constructor variant constructs a new String by decoding the bytes array using given Charset. Since, this constructor throws UnsupportedEncodingException, we must either add throws to the current function or surround it with try/catch block.

String str2;
try {
	str2 = new String(byteArray, "UTF-8");
	System.out.println(str2);
} catch (UnsupportedEncodingException e) {
	e.printStackTrace();
}

Full Example

package com.techstackjournal;

import java.io.UnsupportedEncodingException;

public class ByteArrayToString {

	public static void main(String[] args) {
		byte[] byteArray = { 'a', 'b', 'c', 'd', 'e' };
		String str1 = new String(byteArray);
		System.out.println(str1);

		String str2;
		try {
			str2 = new String(byteArray, "UTF-8");
			System.out.println(str2);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

	}

}

Output

abcde
abcde
See also  How to read input from User in Java