ZetCode

Java HexFormat

Last modified: July 14, 2026

This Java HexFormat tutorial shows how to format and parse hexadecimal strings in Java using the HexFormat utility class. We cover creating HexFormat instances, formatting byte arrays to hex strings, parsing hex strings back to bytes, configuring delimiters, prefixes, suffixes, case, and handling individual byte and long conversions.

Hexadecimal

Hexadecimal (hex) is a base-16 number system that uses sixteen distinct symbols: the digits 0-9 to represent values zero to nine, and the letters A-F (or a-f) to represent values ten to fifteen. Hexadecimal is widely used in computing as a human-friendly representation of binary-coded values. Each hexadecimal digit corresponds to four bits, making it concise and readable for representing byte data, memory addresses, colour codes, and cryptographic digests.

In Java, hexadecimal strings are often used to represent binary data such as file contents, network packets, hash values, or encryption keys. Prior to Java 17, developers had to write custom logic or rely on third-party libraries to convert between bytes and hex strings. The HexFormat class, introduced in Java 17, provides a standard, thread-safe utility for this purpose.

Creating HexFormat

The HexFormat class is located in the java.util package. Instances are created using factory methods rather than public constructors.

HexFormat hf = HexFormat.of();
HexFormat hfUpper = HexFormat.of().withUpperCase();
HexFormat hfDelim = HexFormat.ofDelimiter(":");

HexFormat.of() creates a default instance with lowercase hex digits. The withUpperCase method returns a new instance configured to use uppercase letters. The ofDelimiter factory method creates an instance that inserts the specified delimiter between bytes when formatting.

Formatting byte arrays to hex strings

The formatHex method converts a byte array into a hexadecimal string representation.

Main.java
import java.util.HexFormat;

void main() {

    byte[] data = {0x4A, 0x61, 0x76, 0x61, 0x21};

    HexFormat hf = HexFormat.of();
    String hex = hf.formatHex(data);

    System.out.println(hex);
}

We create a byte array containing the ASCII values of the word "Java!" and format it as a hexadecimal string.

byte[] data = {0x4A, 0x61, 0x76, 0x61, 0x21};

The byte array holds the bytes for the characters J, a, v, a, ! in hexadecimal literal notation.

HexFormat hf = HexFormat.of();
String hex = hf.formatHex(data);

A default HexFormat instance is created and the formatHex method converts the byte array to a lowercase hex string.

$ java Main.java
4a61766121

Formatting a range of bytes

The formatHex method also accepts start and end indices to format only a portion of a byte array.

Main.java
import java.util.HexFormat;

void main() {

    byte[] data = {0x4A, 0x61, 0x76, 0x61, 0x20,
                   0x63, 0x6F, 0x64, 0x65};

    HexFormat hf = HexFormat.of();
    String hex = hf.formatHex(data, 5, 9);

    System.out.println(hex);
}

This example formats bytes from index 5 (inclusive) to 9 (exclusive) of the data array.

String hex = hf.formatHex(data, 6, 11);

We call formatHex with the start index 5 and end index 9, which corresponds to the bytes for "code".

$ java Main.java
636f6465

Uppercase hex formatting

To produce uppercase hexadecimal digits, we use the withUpperCase method.

Main.java
import java.util.HexFormat;

void main() {

    byte[] data = {0x4A, 0x61, 0x76, 0x61, 0x21};

    HexFormat hf = HexFormat.of().withUpperCase();
    String hex = hf.formatHex(data);

    System.out.println(hex);
}

The withUpperCase method returns a new HexFormat instance configured to use uppercase hex letters.

$ java Main.java
4A61766121

HexFormat with delimiter

We can configure a delimiter that is inserted between each byte in the formatted output using withDelimiter or the ofDelimiter factory method.

Main.java
import java.util.HexFormat;

void main() {

    byte[] data = {0x4A, 0x61, 0x76, 0x61, 0x21};

    HexFormat hf = HexFormat.ofDelimiter(" ");
    String hex = hf.formatHex(data);

    System.out.println(hex);

    HexFormat hf2 = HexFormat.of().withDelimiter(":").withUpperCase();
    String hex2 = hf2.formatHex(data);

    System.out.println(hex2);
}

We create HexFormat instances with delimiters.

HexFormat hf = HexFormat.ofDelimiter(" ");
String hex = hf.formatHex(data);

The ofDelimiter factory method creates an instance that inserts a space between formatted bytes.

HexFormat hf2 = HexFormat.of().withDelimiter(":").withUpperCase();
String hex2 = hf2.formatHex(data);

We chain withDelimiter and withUpperCase to create a colon-delimited uppercase hex string.

$ java Main.java
4a 61 76 61 21
4A:61:76:61:21

HexFormat with prefix and suffix

The withPrefix and withSuffix methods add a prefix and suffix to each formatted byte.

Main.java
import java.util.HexFormat;

void main() {

    byte[] data = {0x00, 0x01, 0x02, (byte) 0xFF};

    HexFormat hf = HexFormat.of()
            .withPrefix("0x")
            .withDelimiter(", ")
            .withUpperCase();

    String hex = hf.formatHex(data);

    System.out.println(hex);
}

This example configures a HexFormat that prefixes each byte with 0x, separates bytes with a comma and space, and uses uppercase hex digits.

$ java Main.java
0x00, 0x01, 0x02, 0xFF

Parsing hex strings to byte arrays

The parseHex method converts a hexadecimal string back into a byte array.

Main.java
import java.util.HexFormat;
import java.util.Arrays;

void main() {

    String hex = "48656C6C6F";

    HexFormat hf = HexFormat.of().withUpperCase();
    byte[] data = hf.parseHex(hex);

    System.out.println(Arrays.toString(data));
}

We parse an uppercase hexadecimal string back into a byte array.

byte[] data = hf.parseHex(hex);

The parseHex method interprets each pair of hex digits as one byte and returns the corresponding byte array.

$ java Main.java
[72, 101, 108, 108, 111]

Parsing hex strings with delimiter

When parsing, the HexFormat automatically handles the delimiter if one was configured.

Main.java
import java.util.HexFormat;
import java.util.Arrays;

void main() {

    String hex = "48:65:6C:6C:6F";

    HexFormat hf = HexFormat.ofDelimiter(":");
    byte[] data = hf.parseHex(hex);

    System.out.println(Arrays.toString(data));
}

We parse a colon-delimited hex string. The HexFormat uses the same delimiter configuration for both formatting and parsing.

$ java Main.java
[72, 101, 108, 108, 111]

Converting a single byte to hex digits

The toHexDigits method converts a single byte value into a two-character hexadecimal string.

Main.java
import java.util.HexFormat;

void main() {

    HexFormat hf = HexFormat.of();

    String hex1 = hf.toHexDigits((byte) 0xAB);
    System.out.println(hex1);

    String hex2 = hf.toHexDigits((byte) 0x0F);
    System.out.println(hex2);

    String hex3 = hf.toHexDigits((byte) 255);
    System.out.println(hex3);
}

The toHexDigits method always produces a two-digit hex string, including a leading zero if necessary.

$ java Main.java
ab
0f
ff

Converting a long value to hex digits

The overloaded toHexDigits method also accepts a long value, producing a 16-character hexadecimal string.

Main.java
import java.util.HexFormat;

void main() {

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

    long value = 0xABCD1234EF56L;
    String hex = hf.toHexDigits(value);

    System.out.println(hex);
}

This example converts a long value to a 16-digit uppercase hex string.

$ java Main.java
0000ABCD1234EF56

The toHexDigits(long) method always produces a full 16-character string, zero-padded on the left.

Creating a hex dump

We can combine formatting options to create a readable hex dump of binary data.

Main.java
import java.util.HexFormat;

void main() {

    byte[] data = "The quick brown fox jumps over the lazy dog".getBytes();

    HexFormat hf = HexFormat.of().withUpperCase().withDelimiter(" ");

    for (int i = 0; i < data.length; i += 16) {

        int end = Math.min(i + 16, data.length);
        String hex = hf.formatHex(data, i, end);

        System.out.printf("%04x: %s%n", i, hex);
    }
}

This example produces a formatted hex dump with offset addresses and uppercase hex bytes separated by spaces.

$ java Main.java
0000: 54 68 65 20 71 75 69 63 6B 20 62 72 6F 77 6E 20
0010: 66 6F 78 20 6A 75 6D 70 73 20 6F 76 65 72 20 74
0020: 68 65 20 6C 61 7A 79 20 64 6F 67

Parsing hex string to long

The fromHexDigits method parses a hexadecimal string into a long value.

Main.java
import java.util.HexFormat;

void main() {

    HexFormat hf = HexFormat.of();

    long val1 = hf.fromHexDigits("FF");
    System.out.println(val1);

    long val2 = hf.fromHexDigits("1A3F");
    System.out.println(val2);
}

The fromHexDigits method parses up to 16 hex digits into a long value.

$ java Main.java
255
6719

There is also fromHexDigitsToLong which is the same method; the two names exist for consistency with the toHexDigits method.

Validating hex digits

The isHexDigit and fromDigit static methods are useful for validating and converting individual hex characters.

Main.java
import java.util.HexFormat;

void main() {

    char[] chars = {'0', '7', 'A', 'a', 'F', 'f', 'G', 'z'};

    for (char ch : chars) {

        boolean isHex = HexFormat.isHexDigit(ch);

        if (isHex) {
            int val = HexFormat.fromDigit(ch);
            System.out.printf("'%s' is a hex digit with value %d%n", ch, val);
        } else {
            System.out.printf("'%s' is NOT a hex digit%n", ch);
        }
    }
}

We test several characters with the static utility methods.

boolean isHex = HexFormat.isHexDigit(ch);

The isHexDigit method returns true if the character is a valid hexadecimal digit (0-9, a-f, A-F).

int val = HexFormat.fromDigit(ch);

The fromDigit method returns the integer value of a hex digit character.

$ java Main.java
'0' is a hex digit with value 0
'7' is a hex digit with value 7
'A' is a hex digit with value 10
'a' is a hex digit with value 10
'F' is a hex digit with value 15
'f' is a hex digit with value 15
'G' is NOT a hex digit
'z' is NOT a hex digit

Formatting a colour code

HexFormat is useful for generating hexadecimal colour codes used in web design.

Main.java
import java.util.HexFormat;

void main() {

    byte r = (byte) 0x4A;
    byte g = (byte) 0x90;
    byte b = (byte) 0xD9;

    HexFormat hf = HexFormat.of().withUpperCase().withPrefix("#")
            .withDelimiter("");

    String hex = hf.formatHex(new byte[]{r, g, b});

    System.out.println(hex);
}

This example formats RGB byte values into a web colour code.

HexFormat hf = HexFormat.of().withUpperCase().withPrefix("#")
        .withDelimiter("");

We set the prefix to # and use an empty delimiter so the bytes are concatenated without separation. The result is a standard hex colour code.

$ java Main.java
#4A90D9

Formatting an MD5 hash

The following example computes an MD5 hash of a string and formats the resulting byte array as a hexadecimal string.

Main.java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;

void main() throws NoSuchAlgorithmException {

    String msg = "Hello there!";

    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] digest = md.digest(msg.getBytes());

    HexFormat hf = HexFormat.of().withLowerCase();
    String hex = hf.formatHex(digest);

    System.out.println(hex);
}

We compute an MD5 digest and format it as a 32-character hexadecimal string.

Warning: MD5 is a weak hash algorithm and should not be used for hashing passwords or in security-sensitive contexts. It is still commonly used for non-security tasks such as verifying file integrity, generating checksums, or checking identity against known values. This example is for demonstration purposes only.
$ java Main.java
a77b55332699835c035957df17630d28

Source

Java HexFormat - Language Reference

In this article, we have worked with Java HexFormat.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than eight years of experience in teaching programming.

View all Java tutorials.