Grails Cookbook - A collection of tutorials and examples

Byte Array to String in Java

There are programming scenarios where we have a data in byte array that represents a String. This could be a case when we use a third party library to load data somewhere and the result is a byte array. In such cases, we may want to convert back the byte array to a String. Below are some examples on how to convert a byte array to String in Java.

Wrong Approach

All objects in Java supports the toString() method to convert any data type to a String object. The mechanism is that Java classes should override the toString() method. Unfortunately, byte arrays don't implement the toString() method, hence if we use it, the implementation of the Object class is invoked. The result therefore is not what we expect it to be. For example, this code:

public static void main( String[] args )
{
    String sample = "hello";
    byte[] byteArray = sample.getBytes();
    String convertedString = byteArray.toString();
    System.out.println( convertedString );
}

Will output something like below, which is wrong. What we expect is that the output will also be "hello".

[B@5451c3a8

This is because the toString() method of the Object class is this:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Byte[] array to String

The right way for converting a byte array to Java is shown below:

public static void main( String[] args )
{
    String sample = "hello";
    byte[] byteArray = sample.getBytes();
    String convertedString = new String( byteArray );
    System.out.println( convertedString );
}

This will output the expected result:

hello

Because the constructor of the String class that accepts a byte array parameter behaves correctly.