Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:


1. Introduction

In Java, we usually write our own methods to handle conversions between bytes and hexadecimal strings. However, Java 17 introduces java.util.HexFormat, a utility class that enables the conversion of primitive types, byte arrays, or char arrays to a hex string and vice versa.

In this tutorial, we’ll explore how to use HexFormat and demonstrate the functionality it provides.

2. Dealing with Hex Strings Before Java 17

The hexadecimal numbering system uses a base of 16 to represent numbers. This means it consists of 16 symbols, usually the symbols 0-9 for values from 0 to 9, and A-F for values from 10 to 15.

This is a popular choice for representing long binary values since it’s much easier to reason about compared to binary strings of 1s and 0s.

When we need to convert between hexadecimal strings and byte arrays, developers typically write their own method using String.format() to do the work for them.

This is a simple and easy to understand implementation but tends to be inefficient:

public static String byteArrayToHex(byte[] a) {
    StringBuilder sb = new StringBuilder(a.length * 2);
    for (byte b: a) {
       sb.append(String.format("%02x", b));
    return sb.toString();

Another popular solution is to use the Apache Commons Codec library, which contains a Hex utility class:

String foo = "I am a string";
byte[] bytes = foo.getBytes();

One of our other tutorials explains different ways to manually perform this conversion.

3. HexFormat Usage in Java 17

HexFormat can be found in the Java 17 standard library and can handle conversions between bytes and hexadecimal strings. It also supports several formatting options.

3.1. Creating a HexFormat

How we create a new instance of HexFormat depends on whether we want delimiter support or not. HexFormat is thread-safe, so one instance can be used in multiple threads.

HexFormat.of() is the most common use case, which we use when we don’t care for delimiter support:

HexFormat hexFormat = HexFormat.of();

HexFormat.ofDelimiter(“:”) can be used for delimiter support, this example using a colon as the delimiter:

HexFormat hexFormat = HexFormat.ofDelimiter(":");

3.2. String Formatting

HexFormat allows us to add prefix, suffix, and delimiter formatting options to existing HexFormat objects. We can use these to control the formatting of the String that is being parsed or produced.

Here’s an example of using all three together:

HexFormat hexFormat = HexFormat.of().withPrefix("[").withSuffix("]").withDelimiter(", ");
assertEquals("[48], [0c], [11]", hexFormat.formatHex(new byte[] {72, 12, 17}));

In this case, we’re creating the object using the simple of() method and then adding the delimiter using withDelimiter().

3.3. Bytes and Hexadecimal String Conversion

Now that we’ve seen how to create a HexFormat instance, let’s go over how we can perform conversions.

We’ll use the simple method of creating an instance:

HexFormat hexFormat = HexFormat.of();

Next, let’s use this to convert a String to byte[]:

byte[] hexBytes = hexFormat.parseHex("ABCDEF0123456789");
assertArrayEquals(new byte[] { -85, -51, -17, 1, 35, 69, 103, -119 }, hexBytes);

And back again:

String bytesAsString = hexFormat.formatHex(new byte[] { -85, -51, -17, 1, 35, 69, 103, -119});
assertEquals("ABCDEF0123456789", bytesAsString);

3.4. Primitive Type to Hexadecimal String Conversion

HexFormat also supports the conversion of primitive types to hexadecimal strings:

String fromByte = hexFormat.toHexDigits((byte) 64);
assertEquals("40", fromByte);

String fromLong = hexFormat.toHexDigits(1234_5678_9012_3456L);
assertEquals("000462d53c8abac0", fromLong);

3.5. Uppercase and Lowercase Output

As the examples show, the default behavior of HexFormat is to produce a lowercase hexadecimal value. We can change this behavior by calling withUpperCase() when creating our HexFormat instance:

upperCaseHexFormat = HexFormat.of().withUpperCase();

Even though lowercase is the default behavior, a withLowerCase() method also exists. This is useful to make our code self-documenting and explicit for other developers.

4. Conclusion

The introduction of HexFormat in Java 17 solves many issues that we traditionally face when performing conversions between bytes and hexadecimal strings.

We’ve been through the most common use cases in this article, but HexFormat also supports more niche functionality. For example, there are more conversion methods and the ability to manage the upper and lower half of a full byte.

Official documentation for HexFormat is available in the Java 17 docs.

As usual, the examples we presented in this article are over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.