eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

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 – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

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.

eBook Jackson – NPI EA – 3 (cat = Jackson)