How to convert Byte[] array to String in Java

In Java, we can use new String(bytes, StandardCharsets.UTF_8) to convert a byte[] to a String.

JavaSample.java

package com.mkyong.io;

import java.nio.charset.StandardCharsets;

public class JavaSample {

    public static void main(String[] args) {

        String example = "This is raw text!";
        byte[] bytes = example.getBytes();

        System.out.println("Text : " + example);
        System.out.println("Text [Byte Format] : " + bytes);
        // no, don't do this, it returns the address of the object in memory
        System.out.println("Text [Byte Format] : " + bytes.toString());

        // convert bytes[] to string
        String s = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("Output : " + s);

        // UnsupportedEncodingException
        //String s = new String(bytes, "UTF_8");

    }

}

Output


Text : This is raw text!
Text [Byte Format] : [B@5ae9a829
Text [Byte Format] : [B@5ae9a829
Output : This is raw text!
author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
newest oldest most voted
Pablo
Guest
Pablo

In most cases,

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

is best.

Shiva
Guest
Shiva

Thank You. This Helped.

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 »

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

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/ […]

vj
Guest
vj

thnx a lot…saved ma day 😛

betty
Guest
betty

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

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

Paul
Guest
Paul

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

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!

sandy
Guest
sandy

This is returning hashcode..not bytes

LM
Guest
LM

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

rohan
Guest
rohan

This helped and saved time for a newbie like me 🙂

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

saidtak
Guest
saidtak

The issue I find with this byte string conversion is starting from byte{], convert it to String, then retrieve the original byte{} again!

The most stable solution I found so far is using sun.misc.BASE64Encoder().encode(myByte) and sun.misc.BASE64Decoder().decodeBuffer(myString) but with a java sun warning!

Any one with a better solution?

saidtak
Guest
saidtak

byt[] of course!

ThePCWizard
Guest
ThePCWizard

Thanks, for sharing such simple codes. it helps!

Mic and Rud
Guest
Mic and Rud

YOU ARE THE MAN!!

ogda
Guest
ogda

Thank you 🙂

Diljeet
Guest
Diljeet

Thanks for sharing

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.

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.

Abhijith
Guest
Abhijith

Thanks man. That helped.

Karthik SR
Guest
Karthik SR

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

subhash M
Guest
subhash M

Thank you

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 »

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);

}

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

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 »

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/ […]

Yuvraj
Guest
Yuvraj

This is helpful solution…

sahil
Guest
sahil

Hi!!, Do you have anything on converting a string to Octet String in Java. I tried but couldn’t get anything concrete.