Java – Byte Array to String conversion

In this article, we will discuss how to convert Byte[] array to String in Java

1. Byte:

  • Size is 1 byte
  • Its range is -128 to 127

Need:

  • Sometimes, it is important to convert byte[] array to String for displaying purpose

2. Converting byte[] array to String :

  • Create new String object passing byte[] array as constructor-argument
  • Note: The value range should be within -128 to 127

Method signature:

public String(byte bytes[]);

ConvertByteArrayToStringUsingNewStringObject.java

package in.bench.resources.bytes.to.string.conversion;

import java.util.Arrays;

public class ConvertByteArrayToStringUsingNewStringConstructor {

	public static void main(String[] args) {

		// primitive byte[] array
		byte[] byteArray1 = {66, 69, 78, 67, 72};

		// original Byte[] array
		System.out.println("1.1 Original byte[] array : "
				+ Arrays.toString(byteArray1));

		// 1. converting byte[] array to String
		String str1 = new String(byteArray1);
		System.out.println("1.2 Converted"
				+ " byte[] array to String value is : "
				+ str1);

		// sample string
		String res = "Resources";

		// original String
		System.out.println("\n\n2.1 Original String value : "
				+ res);

		// String to byte[] array
		byte[] byteArray2 = res.getBytes();

		System.out.println("2.2 Converted"
				+ " String in Byte format : "
				+ byteArray2);

		// 2. byte[] array to String
		String str2 = new String(byteArray2);
		System.out.println("2.3 Converted"
				+ " byte[] array to String value is : "
				+ str2);
	}
}

Output:

1.1 Original byte[] array : [66, 69, 78, 67, 72]
1.2 Converted byte[] array to String value is : BENCH

2.1 Original String value : Resources
2.2 Converted String in Byte format : [B@1db9742
2.3 Converted byte[] array to String value is : Resources

Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - String to short conversion in 3 ways
Java - String to Byte[] Arrays conversion