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 – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Overview

Bit manipulation is a fundamental concept in programming that involves working with individual bits of binary data. One common operation is flipping all bits in an integer, converting every 0 to 1 and every 1 to 0.

In this tutorial, we’ll explain what bit flipping means and explore several Java methods to flip the bits of an integer. For completeness, we’ll cover both full 32-bit flipping and flipping only the significant bits.

2. Understanding Bit Flipping

Before we learn how to flip bits in an integer, it’s best to look at a visual example.

To begin with, let’s consider the decimal number 21 and, more specifically, its binary representation:

10101

The goal is to invert each bit so that every 0 becomes a 1 and every 1 becomes a 0:

01010

This corresponds to the decimal value 10 (8+2).

During this transformation, each bit at position i in the original number gets inverted in the result. However, there’s an important distinction to make. When we flip all 32 bits of an integer, i.e., its full size, the result differs from flipping only the significant bits. For instance, flipping all 32 bits of the integer 21 produces -22 due to two’s complement representation, whereas flipping only the significant bits (10101 -> 01010) yields 10.

In the following sections, let’s explore both scenarios in detail.

3. Using the Bitwise NOT Operator

The most direct approach to flip bits is the bitwise NOT operator ~. This unary operator inverts every bit in the integer’s binary representation:

public static int flipAllBits(int n) {
    return ~n;
}

The operator flips all 32 bits of the integer. This means that ~ inverts every bit, including leading zeros, turning a positive number into a negative one due to the two’s complement representation in Java.

Let’s verify the results using a JUnit 5 test and AssertJ matchers:

@Test
void givenPositiveInteger_whenFlipAllBits_thenReturnsNegativeComplement() {
    assertThat(flipAllBits(21)).isEqualTo(-22);
    assertThat(flipAllBits(0)).isEqualTo(-1);
    assertThat(flipAllBits(-1)).isEqualTo(0);
}

As we can see, flipping all 32 bits of 21 gives us -22, not 10. This is because Java’s int type is a signed 32-bit integer.

To get a result like 10 from 21, we need to flip only the significant bits. Let’s cover this case next.

4. Flipping Only the Significant Bits

In many practical scenarios, we want to flip only the bits that are actually used in the binary representation of the number, excluding leading zeros. For instance, flipping the significant bits of 21 (10101) should give us 10 (01010).

4.1. Using a Mask With Bit Length Calculation

The idea is straightforward: we create a mask with a 1 at each significant bit position, then XOR the number with this mask. The XOR operation flips only the bits where the mask has a 1:

public static int flipSignificantBits(int n) {
    if (n == 0) {
        return 0;
    }
    int bitLength = Integer.SIZE - Integer.numberOfLeadingZeros(n);
    int mask = (1 << bitLength) - 1;
    return n ^ mask;
}

First, we handle the edge case where n is 0. Then, we calculate the number of significant bits using Integer.numberOfLeadingZeros(). With this value, we create a mask by shifting 1 left by bitLength positions and subtracting 1, which gives us a sequence of 1s matching the significant bit length.

Finally, the XOR operation (^) flips only the significant bits, since XOR with 1 inverts a bit while XOR with 0 leaves it unchanged.

Let’s verify this with a test:

@Test
void givenPositiveInteger_whenFlipSignificantBits_thenReturnsFlippedValue() {
    assertThat(flipSignificantBits(21)).isEqualTo(10);
    assertThat(flipSignificantBits(26)).isEqualTo(5);
    assertThat(flipSignificantBits(0)).isEqualTo(0);
    assertThat(flipSignificantBits(1)).isEqualTo(0);
    assertThat(flipSignificantBits(7)).isEqualTo(0);
}

To illustrate, let’s trace through the example with 26 (binary 11010):

n     = 11010  (26)
mask  = 11111  (31)
n ^ mask = 00101  (5)

This approach effectively and efficiently flips only the significant bits.

4.2. Using Integer.highestOneBit()

We can also use the built-in Integer.highestOneBit() method to build the mask. This method returns a value with only the highest bit of the input set:

public static int flipSignificantBitsUsingHighestOneBit(int n) {
    if (n == 0) {
        return 0;
    }
    int mask = (Integer.highestOneBit(n) << 1) - 1;
    return n ^ mask;
}

Here, Integer.highestOneBit(n) returns the value of the most significant bit. By shifting it left by one position and subtracting 1, we create a mask with a 1 at each significant bit. Then, a XOR operation with this mask again flips only those bits.

4.3. Using the Bitwise NOT With a Mask

Instead of XOR, we can also combine the bitwise NOT operator with a mask to get the same result:

public static int flipSignificantBitsUsingNot(int n) {
    if (n == 0) {
        return 0;
    }
    int bitLength = Integer.SIZE - Integer.numberOfLeadingZeros(n);
    int mask = (1 << bitLength) - 1;
    return ~n & mask;
}

This function first computes the bitwise NOT of n, which flips all 32 bits. Then, the AND operation with the mask zeroes out all the bits beyond the significant ones. Simply put, the result is equivalent to flipping only the significant bits.

5. Alternative Methods

Apart from the standard bitwise operators, there are other, more unorthodox ways to flip all 32 bits of an integer.

5.1. Using Arithmetic Negation

Due to the two’s complement representation, flipping all bits of n is equivalent to computing -n – 1:

public static int flipBitsArithmetic(int n) {
    return -n - 1;
}

This works because, in two’s complement, the negation of n is the bitwise complement plus 1 (-n = ~n + 1). Therefore, ~n = -n – 1, which gives the same result as the bitwise NOT operator.

5.2. Using XOR With -1

Another way to flip all bits is to XOR the number with -1. In binary, we represent -1 as all 1s (11111111…1 in 32 bits). Notably, ~0 also evaluates to -1, so we can use either interchangeably:

public static int flipBitsXorMinusOne(int n) {
    return n ^ -1;
}

Since XOR with 1 flips a bit, performing XOR with a value where all bits are 1 effectively flips every bit in the integer. This produces the same result as the ~ operator.

6. Conclusion

In this article, we explored several approaches for flipping bits of an integer in Java. We started with the bitwise NOT operator for full 32-bit flipping. Next, we looked at mask-based methods for flipping only the significant bits using XOR and AND operations. Finally, we covered alternative approaches using arithmetic negation and XOR.

As always, all the source code is available over on GitHub.

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.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

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