How to convert a byte array to hex string in Java

In this Java tutorial, we are going to learn how to convert byte array to hex string in Java. This post will be easy to understand for you. This is CodeSpeedy so here we are going to give you the easiest example for you so that you can understand it easily.

how to convert Object array to String array in java

So basically we need the following in order to convert a byte array to hex string in Java

  • byte[] array
  • String.format() method

Convert byte array to hex string in Java

The below Java Program is an easy example of How to convert a byte array to a hex String in Java

public class MyConversion {

    public static void main(String args[]) {
           byte[] my_byte_array = {48, 98, 74, 51}; // This is a byte array

           for (byte byte_to_be_converted: my_byte_array ) {
               String my_hex_string = String.format("%02X", byte_to_be_converted); // this is a hex string now
               System.out.println(my_hex_string ); // this line will print the hex string



my_byte_array is a byte array variable. We have stored some numeric elements in this byte array variable.

Next, with the help of for loop, we converted each element of the byte array to hex string one by one until we have finished all the elements.

String.format("%02X", byte_to_be_converted);

Then finally, We print the converted elements.

Always remember, this is not one and only solution for your problem. You can use other methods too. I found this method useful and easy to understand. That’s why I have shared this with you. If you wish you can try other methods too. In the beginning, It is always better to find a solution without any help. If you are not able to find a solution then only go for help. After all, practice makes a skill perfect.

Also read,

How to convert BLOB to Byte Array in java

How to convert Byte Array to Image in java with easy example


Leave a Reply

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