Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

In this tutorial, we’ll learn how to convert an integer value to hexadecimal in Java. We’ll discuss the different methods available using code examples.

2. Convert Integer to Hexadecimal in Java

Before jumping into some code examples, let’s learn how integer to hexadecimal conversion works.

Integer numbers use a decimal base(10), i.e., numbers from 0 to 9. However, hexadecimal values are represented by only 16 symbols, 0 to 9 and A to F.

There are different ways to convert an integer value into a hexadecimal in Java. We can use a mathematical-based approach, some Java built-in functionalities, or third-party libraries. We’ll see each one of them in the following sections.

3. Raw Method

First, we’ll start using a simple mathematical algorithm to convert our input integer data:

  1. Divide the integer by 16
  2. Divide the result of the division by 16
  3. Take the remainder of the division and convert it to a hexadecimal digit
  4. Repeat steps one and two until the result of the division is 0

Let’s build up our custom converter class based on the above algorithm:

class IntegerToHex {
    static final String digits = "0123456789ABCDEF";
    static String integerToHex(int input) {
        if (input <= 0)
            return "0";
        StringBuilder hex = new StringBuilder();
        while (input > 0) {
            int digit = input % 16;
            hex.insert(0, digits.charAt(digit));
            input = input / 16;
        }
        return hex.toString();
    }
}

The above code uses the described algorithm to get the hex value from the input integer.

Next, let’s test our method:

@Test
void givenIntegerValue_whenUseRawMethod_thenWillGetHexValue() {
    String result = IntegerToHex.integerToHex(1055);
    assertEquals("41F", result);
}

The drawback of our implementation is that it only accepts positive integers greater than zero.

4. String format() Method

The next method comes from the String class, the format() method. In this case, we use the %x specifier to get the hex format output. Let’s test this behavior:

@Test
void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValue() {
    String result = String.format("%02x", 255);
    assertEquals("ff", result);
}

The format() method formats 255 as a two-digit hexadecimal number in our code example.

We can change the number of left padding zeros in the resulting hexadecimal by changing the number in the specifier. Let’s replace %02x with the %04x specifier in our next test:

@Test
void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValueWithLeftZeros() {
    String result = String.format("%04x", 255);
    assertEquals("00ff", result);
}

We can notice from our previous test case that the expected result changed from the initial “ff” to “00ff” when the specifier changed to %04x.

If we need the result hex value in upper case, we only need to change “x” by “X” in the format specifier:

@Test
void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValueWithLeftZerosAndUpperLetter() {
    String result = String.format("%04X", 255);
    assertEquals("00FF", result);
}

5. Using toHexString() Method

Our next option is using toHexString(), present in both Integer and Long classes.

The static toHexString() method under the hood calls the toUnsignedString() method. In both cases, it converts the input value to an unsigned value. That’s why we need to avoid passing negative values to this method.

Let’s code some test cases to illustrate both uses. The first test case uses the toHexString() from the Integer class:

@Test
void givenIntegerValue_whenUseIntegerToHexString_thenWillGetHexValue() {
    String result = Integer.toHexString(1000);
    assertEquals("3e8", result);
}

Our next test is for the toHexString() method from the Long class:

@Test
void givenIntegerValue_whenUseLongToHexString_thenWillGetHexValue() {
    String result = Long.toHexString(255L);
    assertEquals("ff", result);
}

In the case of the first test, the input data for the toHexString() method was an Integer value. In the second test, the input data we passed as an argument to the method was a Long value.

6. Using toString() Method

In addition to the toHexString() method in the Integer and Long classes, we have the toString() method. This method takes two arguments and returns a string representing the first parameter using the radix defined by the second argument. For our case, the radix is 16 because we need the hex representation.

Let’s use the toString() method in the Integer class:

@Test
public void givenNegativeIntegerValue_whenUseIntegerToString_thenWillGetHexValue() {
    String result = Integer.toString(-1458, 16);
    assertEquals("-5b2", result);
}

In the above test case, we pass a negative integer with radix 16 to the toString() method. The result is a negative hex value. In contrast to earlier approaches, in which the data being input was only positive integers, the toString() method converts signed integers into signed hex values.

Our second test is similar to the first one, but we’ll use the toString() method in the Long class:

@Test
public void givenLongValue_whenUseLongToString_thenWillGetHexValue() {
    String result = Long.toString(158, 16);
    assertEquals("9e", result);
}

In this case, the toString() method works like the toString() method with the Integer class but with a long value as input data.

7. Apache Commons Codec Library

Finally, another way to get a hex value is using a third party-library like Apache Commons Codec. From Apache Commons Codec, we use the Hex class and the static method  encodeHexString()

We need to add the Apache Commons Codec dependency to our pom.xml file:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version>
</dependency>

Now, we’re ready to implement our test case:

@Test
public void givenIntegerValue_whenUseApacheCommons_thenWillGetHexSignedValue() {
    String result = Hex.encodeHexString(new byte[] { (byte) 254 });
    assertEquals("fe", result);
}

In the above test, we passed a byte array as an argument – an array with only one element. We cast the integer input value to the byte data type.

This is the main drawback of this approach because the byte data type in Java is an 8-bit signed two’s complement integer, with values ranging from -128 to 127. For values of less than 255, we can use this approach without any problem.

Similar behavior to this is used by java.util.HexFormat. This feature was introduced in Java 17. The HexFormat class provides a simple and convenient way to convert between byte arrays and their corresponding hexadecimal string representations.

8. Conclusion

In this article, we implemented code examples using different ways to convert integer values into hexadecimal. With a deeper understanding of the code and best practices, we can efficiently execute the conversion and optimize the performance of our code. In our tests, we used both built-in methods and libraries in Java.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW