Java Byte Array To String

Byte Array is a convenient data structure that has many use cases. One scenario is when serializing some object to a file, and so we need to convert object to byte array when we write to file, and convert back from byte array to objects when we read from file. Another scenario is when sending data from one machine to another. Complex data structure is converted to a byte array before sending over the network, and on the other end the byte array is converted back to the original data structure. One of the simplest type of Object that we can convert to and from byte array is a String. This post will show how to convert Java Byte Array To String that can be applied to the use cases mentioned earlier.

Java Byte Array To String Using Wrong Approach

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

This is actually wrong as will be seen by sample output of the code below:


We 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.

Java Byte Array To String Using New Operator

The easiest approach that will give the correct result is by using the new operator and create a String object. Below is the sample code.
byte[] byteArray = "Hello".getBytes();
String convertedString = new String(byteArray);

This will output the correct result shown below:


This is because the constructor of the String object can accept a byte array that can process the parameter correctly.

Java Byte Array To String Using Own Algorithm

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];
String convertedString = sb.toString();

And this prints out the same correct result.