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.out.println("Please enter a string: ");
      String strInput =;
      StringBuffer sb = new StringBuffer();
      char[] chArray = strInput.toCharArray();
      for(int a = 0; a < chArray.length; a++)
         String strHexadecimal = Integer.toHexString(chArray[a]);
      String strOutput = sb.toString();


Please enter a string: flowerbrackets