Java Program to Convert Byte Array to String

There are many ways to change byte arrays to strings in Java. You can use the methods in the JDK, or you can use open-source supplementary APIs such as Apache commons and Google Guava. These APIs provide at least two sets of methods to create strings from byte arrays; one uses the default platform encoding, and the other uses character encoding.

This is also one of the best practices for specifying character encoding when converting bytes to characters in any programming language. Your byte array may contain non-printable ASCII characters. Let's first take a look at the way the JDK converts byte[] to a string. Some programmers also recommend using Charset over String to specify the character encoding, for example, instead of "UTF-8", using StandardCharsets.UTF_8 is mainly to avoid unsupported encoding exceptions in the worst case.

Case 1: Without character encoding

We can convert the byte array into a string of the ASCII character set without even specifying the character encoding. The idea is to pass byte[] to a string. As shown in the following example:

Example:

// Java Program to Convert Byte Array to String
// Without character encoding

// Importing required classes
import java.io.IOException;
import java.util.Arrays;

// Main class
class GFG {
	// Main driver method
	public static void main(String[] args)
		throws IOException
	{
		// Getting bytes from the custom input string
		// using getBytes() method and
		// storing it in a byte array
		byte[] bytes = "Geeksforgeeks".getBytes();

		System.out.println(Arrays.toString(bytes));

		// Creating a string from the byte array
		// without specifying character encoding
		String string = new String(bytes);

		// Printing the string
		System.out.println(string);
	}
}

Output

[71, 101, 101, 107, 115, 102, 111, 114, 103, 101, 101, 107, 115]
Geeksforgeeks

Case 2: With character encoding

 
Example
// Java Program to Convert Byte Array to String
// With character encoding

// Importing required classes
import java.io.IOException;
import java.nio.charset.StandardCharsets;

// Main class
class GFG {

	// Main driver method
	public static void main(String[] args)
		throws IOException
	{

		// Custom input string is converted into array of
		// bytes and stored
		byte[] bytes = "Geeksforgeeks".getBytes(
			StandardCharsets.UTF_8);

		// Creating a string from the byte array with
		// "UTF-8" encoding
		String string
			= new String(bytes, StandardCharsets.UTF_8);

		// Print and display the string
		System.out.println(string);
	}
}

Output

Geeksforgeeks

That’s all about converting a byte array to Java String.

Submit Your Programming Assignment Details