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.

<br />
package com.programtalk.beginner.tutorial;<br />
public class ByteToString<br />
{<br />
	public static void main(String[] cheese) {</p>
<p>		    String simpleString = &quot;programtalk.com example&quot;;<br />
		    System.out.println(&quot;print string  : &quot; + simpleString);</p>
<p>		    // get bytes from string<br />
		    byte[] bytes = simpleString.getBytes();<br />
		    System.out.println(&quot;print byte Format : &quot; + bytes);<br />
		    System.out.println(&quot;print byte.toString() : &quot; + bytes.toString());</p>
<p>		    // convert byte[] to string<br />
		    String stringFromByte = new String(bytes);<br />
		    System.out.println(&quot;text from byte : &quot; + stringFromByte);</p>
<p>	}<br />
}<br />

output :

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

 

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.