how to convert Byte[] array to String in Java

In some cases, we have to convert String variable into a Byte array format, for example, JCE encryption. However how do we convert a Byte[] array to String afterward?

Simple toString() function like following code is not working property. It will not display the original text but byte value.


String s = bytes.toString();

In order to convert Byte array into String format correctly, we have to explicitly create a String object and assign the Byte array to it.


String s = new String(bytes);

public class TestByte
{    
	public static void main(String[] argv) {

		    String example = "This is an example";
		    byte[] bytes = example.getBytes();

		    System.out.println("Text : " + example);
		    System.out.println("Text [Byte Format] : " + bytes);
		    System.out.println("Text [Byte Format] : " + bytes.toString());

		    String s = new String(bytes);
		    System.out.println("Text Decryted : " + s);
		    

	}
}

Output


Text : This is an example
Text [Byte Format] : [B@187aeca
Text [Byte Format] : [B@187aeca
Text Decryted : This is an example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Pablo
Guest
Pablo

In most cases,

new String(bytes, "UTF-8");

is best.

Jonathan Paugh
Guest
Jonathan Paugh

The value returned by array.toString() is *not* the binary representation of the array’s elements. It is the default toString() method implemented by Object, and it returns the address of the object in memory. See here: http://stackoverflow.com/a/36994589/712526

Incidentally, this is why String.valueOf(bytes) does not work, either.

Raja Nasir
Guest
Raja Nasir
Hello Mkyong! Please correct me if i am wrong. Just see ur article but it seems its mostly misguided. “Simple toString() function like following code is not working property. It will not display the original text but byte value.” toString is working properly if you see the documentation you will know. So lets c the behavior of this method System.out.println(“Text [Byte Format] : ” + bytes); System.out.println(“Text [Byte Format] : ” + bytes.toString()); OutPut: Text [Byte Format] : [B@187aeca Text [Byte Format] : [B@187aeca The both above lines are same if you use bytes in Print method it will automatically… Read more »
trackback
compress and decompress String using DeflaterOutputStream and InflaterInputStream in java  |  Stackforum.com

[…] I don’t where exactly is the problem . I though it’s in converting the byte array to String but I tried it and it is working. You can check this website http://www.mkyong.com/java/how-do-convert-byte-array-to-string-in-java/ […]

trackback
compress and decompress String using DeflaterOutputStream and InflaterInputStream in java | StackAnswer.com

[…] I don’t where exactly is the problem . I though it’s in converting the byte array to String but I tried it and it is working. You can check this website http://www.mkyong.com/java/how-do-convert-byte-array-to-string-in-java/ […]

Alexej Geldt
Guest
Alexej Geldt
Hello Mkyong! I have exprienced odd behavior when i try to convert a serialized map to a string. My intention is to serialize a map containing strings, convert it to a readable string, and then deserialize it back to map. pls take a look at following example. ——————————————————– import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class TestClient { /** * @param args * @throws IOException * @throws ClassNotFoundException */ public static void main(final String[] args) throws IOException, ClassNotFoundException { final Map map = new HashMap(); final String[] values… Read more »
Amar
Guest
Amar

Thanks for the information. Could you also please let me know how to convert Byte[] (capital B) to String. The above code does not work for the nonprimitive Byte[]. Thank you.

Regards,
Amar

Raptor
Guest
Raptor

Byte is a class, its not a datatype. Whereas byte[] array is a datatype. It will be more clear from the code snippet below:

//—————————————————————————————————————————-//
public static void main (String[] args){

byte b = 18;
Byte wrappedByte = new Byte(b);

}

//—————————————————————————————————————————-//

rushank
Guest
rushank

if we are taking array of string then it will show error….so can i have to do if i want to use string array..
i want to do this… -> String[] s = bytes.toString();

bt it will give me erroe

mahya
Guest
mahya

please tell me a program source code in java that convert text to binary and binary to text.

Raptor
Guest
Raptor
If you want to find the binary of a singular alphabet, then you can make use of Ascii codes as given below: //—————————————————————————————————————————// public class TexttoBinary { public static void main (String[] args){ char ch=’A’; System.out.println((int)ch); // prints ASCII of ‘A’ String text = Integer.toBinaryString(ch); // converts ASCII value to Binary System.out.println(text); } } //————————————————————————————————————————-// If you wish to convert text strings to binary then you can use the below mentioned code: //————————————————————————————————————————-// import java.math.BigInteger; import java.nio.charset.Charset; public class TexttoBinary { public static void main (String[] args){ String str = “Java”; String hex = toHex(str); // converts String to hexadecimal… Read more »
subhash M
Guest
subhash M

Thank you

Karthik SR
Guest
Karthik SR

Thanks sir! Saved me several hours. You are awesome!

Abhijith
Guest
Abhijith

Thanks man. That helped.

Kalyan Kumar
Guest
Kalyan Kumar

I am trying to convert bytes into String. I am reading the image data and storing into byte array. then i think bytes length is so much. Is there any limit for bytes length? Will there be anyloss of data when converting bytes into string.

Kalyan Kumar
Guest
Kalyan Kumar

Dear Mkyong

I am trying to convert bytes into String. Is there any limit for bytes length? Will there be anyloss of data when converting bytes into string.

Diljeet
Guest
Diljeet

Thanks for sharing

ogda
Guest
ogda

Thank you :)

Mic and Rud
Guest
Mic and Rud

YOU ARE THE MAN!!

ThePCWizard
Guest
ThePCWizard

Thanks, for sharing such simple codes. it helps!

DW
Guest
DW

This example relies on a number of assumptions that are important to understand. You should always specify the encoding when converting bytes. Also, the system.out statements show the string representation of the reference to the byte array, not the byte array itself.

This example works since both the byte array and converting it back use the same default encoding of the JVM

rohan
Guest
rohan

This helped and saved time for a newbie like me :)

LM
Guest
LM

oh, thanks a lot. this simple code help me very much.

sandy
Guest
sandy

This is returning hashcode..not bytes

Marty Brouwer
Guest
Marty Brouwer

you are really a good webmaster. The web site loading speed is incredible. It sort of feels that you are doing any distinctive trick. In addition, The contents are masterpiece. you’ve performed a magnificent activity on this subject!

Paul
Guest
Paul

Thank you so much for this! I looked for quite a while before discovering this simple solution. Really appreciate it!

madsci
Guest
madsci

The obvious conversions didn’t work, and older jdbc drivers didn’t require this! Was faced with upgrading old code that still works fine and it took a while to realize that byte[] conversion to String had changed. Then once I got that figured out your page simplified the needed correction. Thanks for showing the examples that don’t work along with the ones that do, and the [B@… craziness too so it was easy to find! Big help!
_M

betty
Guest
betty

Thanks a lot for sharing sample codes. It saves me time!

vj
Guest
vj

thnx a lot…saved ma day :P

darkky
Guest
darkky

[B@187aeca is the memory adress not , bytes is only made from 0 and 1

Tobe from replace
Guest
Tobe from replace

Hey, noob. Bit made from 1, 0 but bytes makes from charactes. 256 bit = 1 byte.

Guest
Guest
Guest

Hey, noob. 8 bits = 1 byte.

Alejandro Casanova
Guest
Alejandro Casanova

Hi. Excellent sample.
I have a question though. It happens to me that sometimes I´m getting OOM error while creating the String object from a byte array “responseAsString = new String(bytes, responseCharSet)” while getting really big byte arrays in Android. Which would be the best approach for creating the String object using a really bug byte array avoiding the OOM?
Thanks!

Hang Pan
Guest
Hang Pan

“following code is not working property”, should be “properly”, right?