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()); }
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:
helloBecause the constructor of the String class that accepts a byte array parameter behaves correctly.