Converting A String To Hexadecimal In Java

To convert a string to a hexadecimal string in Java, you can use the encodeHexString method of the org.apache.commons.codec.binary.Hex class. Here is an example:

import org.apache.commons.codec.binary.Hex;

String input = "Hello World";
String hexString = Hex.encodeHexString(input.getBytes());
System.out.println(hexString); // prints "48656c6c6f20576f726c64"

Alternatively, you can use a loop to manually convert the string to a hexadecimal string:

String input = "Hello World";
StringBuilder hexString = new StringBuilder();
for (char c : input.toCharArray()) {
  hexString.append(Integer.toHexString((int) c));
}
System.out.println(hexString.toString()); // prints "48656c6c6f20576f726c64"

You can also use the printf method to format the hexadecimal string:

String input = "Hello World";
StringBuilder hexString = new StringBuilder();
for (char c : input.toCharArray()) {
  hexString.append(String.format("%02x", (int) c));
}
System.out.println(hexString.toString()); // prints "48656c6c6f20576f726c64"