Convert byte[] array to String in Java

In this tutorial we will see how to convert a byte[] to String. It can be useful in cases where a String is stored as a byte[] array and needs to be converted to String.

Java API Used

This can be easily achieved by using the constructor provided by String class that accepts the byte[] argument.

java.lang.String.String(byte[] bytes)

Important : Constructs a new String by decoding the specified array of bytes using the platform’s default charset.

Example

Here is a simple program to show how to convert byte[] array to String.

package com.programtalk.beginner.tutorial;
public class ByteToString
{
	public static void main(String[] cheese) {

		    String simpleString = "programtalk.com example";
		    System.out.println("print string  : " + simpleString);
		    
		    // get bytes from string
		    byte[] bytes = simpleString.getBytes();
		    System.out.println("print byte Format : " + bytes);
		    System.out.println("print byte.toString() : " + bytes.toString());

		    // convert byte[] to string
		    String stringFromByte = new String(bytes);
		    System.out.println("text from byte : " + stringFromByte);

	}
}

output :

print string  : programtalk.com example
print byte Format : [[email protected]
print byte.toString() : [[email protected]
text from byte : programtalk.com example

 

Like this post? Don’t forget to share it!