String to Hexadecimal
The toHexString() method of the Integer class accepts an integer as a parameter and returns a hexadecimal string. Therefore, to convert a string to a hexadecimal String −
Get the desired String.
Create an empty StringBuffer object.
Convert it into a character array using the toCharArray() method of the String class.
Traverse through the contents of the array created above, using a loop.
Within the loop convert each character of the array into an integer and pass it as a parameter to the toHexString() method of the Integer class.
Append the resultant values to the StringBuffer object using the append() method of the StringBuffer class.
Finally, convert the StringBuffer object to a string using the toString() method of the StringBuffer class.
Example
import java.util.Scanner; public class StringToHexadecimal { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter a String value: "); String str = sc.next(); StringBuffer sb = new StringBuffer(); //Converting string to character array char ch[] = str.toCharArray(); for(int i = 0; i < ch.length; i++) { String hexString = Integer.toHexString(ch[i]); sb.append(hexString); } String result = sb.toString(); System.out.println(result); } }
Output
Enter a String value: Tutorialspoint 5475746f7269616c73706f696e74
Hexadecimal to string
In the same way to convert a hexadecimal (String) value to a String −
Get the hexadecimal value (String).
Convert it into a character array using the toCharArray() method.
Read each two characters from the array and convert them into a String.
Parse above obtained string into base 16 integer, cast it into a character.
Concat all the characters to a string.
Example
import java.util.Scanner; public class HexadecimalToString { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter a Hexadecimal value: "); String str = sc.next(); String result = new String(); char[] charArray = str.toCharArray(); for(int i = 0; i < charArray.length; i=i+2) { String st = ""+charArray[i]+""+charArray[i+1]; char ch = (char)Integer.parseInt(st, 16); result = result + ch; } System.out.println(result); } }
Output
Enter a Hexadecimal value: 5475746f7269616c73706f696e74 Tutorialspoint