[java] Java code To convert byte to Hexadecimal

Java 17: Introducing java.util.HexFormat

Java 17 comes with a utility to convert byte arrays and numbers to their hexadecimal counterparts. Let's say we have an MD5 digest of "Hello World" as a byte-array:

var md5 = MessageDigest.getInstance("md5");
md5.update("Hello world".getBytes(UTF_8));

var digest = md5.digest();

Now we can use the HexFormat.of().formatHex(byte[]) method to convert the given byte[] to its hexadecimal form:

jshell> HexFormat.of().formatHex(digest)
$7 ==> "3e25960a79dbc69b674cd4ec67a72c62"

The withUpperCase() method returns the uppercase version of the previous output:

jshell> HexFormat.of().withUpperCase().formatHex(digest)
$8 ==> "3E25960A79DBC69B674CD4EC67A72C62"