String to hexadecimal in java

Let’s learn string to hexadecimal in java.

String to hexadecimal in java

To convert string to hex java first get input from user using next() method of Scanner class.

In the next step create StringBuffer object. Now convert user entered string to character array using toCharArray() method of String class.

Now using for loop traverse elements of the array. While looping in for loop, convert each character of array into an integer using toHexString() method of Integer class.

Moving on using append() method of StringBuffer class append remaining values to StringBuffer object.

Lastly convert StringBuffer object to string using toString() method of StringBuffer class.

Let’s see an example on java convert string to hex.

import java.util.Scanner;
public class StringToHexJava
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a string: ");
      String strInput = sc.next();
      StringBuffer sb = new StringBuffer();
      char[] chArray = strInput.toCharArray();
      for(int a = 0; a < chArray.length; a++)
      {
         String strHexadecimal = Integer.toHexString(chArray[a]);
         sb.append(strHexadecimal);
      }
      String strOutput = sb.toString();
      System.out.println(strOutput);
      sc.close();
   }
}


Output:

Please enter a string: flowerbrackets
666c6f776572627261636b657473