Java – How to convert a byte array to string

In this post we will show you how to convert a byte array to string in java. Converting a string to a byte array is fairly simple however, vice versa is a little more tricky.

Example: Convert string to byte array:

Converting a string to a byte array is very simple as seen below.

Example: Convert a byte array to string:

Using the byte array toString() method, will not give you the desired result. This will instead return the byte value as a string. To correctly convert the byte array to a string you will need to do the following:

As you can see from the results shown below. The bytes.toString() method does not do what we want. Hence, the reason for creating a new string object (and specifying the charset).

Output:

For more information regarding the java String API you should consult the java documentation which can be found here and information relating to the Byte class can be found here.

Similar posts:

  1. Java String basics
  2. How to convert a String to an Integer
  3. How to convert an InputStream to a String

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *