Since any Java object implements the toString() method, we can be tempted to use this method to convert a byte array to string. Here is a sample code:
byte[] byteArray = "Hello".getBytes(); String convertedString = byteArray.toString(); System.out.println(convertedString);
This is actually wrong as will be seen by sample output of the code below:
[B@2a139a55We are expecting the output "Hello" but we get this unexpected output instead. This is because the above comes from the default implementation from the Object class.
byte[] byteArray = "Hello".getBytes(); String convertedString = new String(byteArray); System.out.println(convertedString);
This will output the correct result shown below:
HelloThis is because the constructor of the String object can accept a byte array that can process the parameter correctly.
If the ready made solution is not palatable and we want to challenge ourselves to write our own solution, we can code our own way. Shown below is an example on how to do it:
byte[] byteArray = "Hello".getBytes(); StringBuilder sb = new StringBuilder(); for (int i=0; i<byteArray.length; i++) { char c = (char) byteArray[i]; sb.append(c); } String convertedString = sb.toString(); System.out.println(convertedString);
And this prints out the same correct result.
Hello