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. Introduction

A power of 2 is a number that can be expressed as 2 raised to some integer power, such as 2, 4, 8, 16, and so on. In Java, there are several ways to determine if a given number is a power of 2, including using logarithms, bitwise operations, loop division, and built-in methods. In this tutorial, we’ll explore these different methods and provide examples of how to implement them in Java.

2. Loop Division

One way to check if a number is a power of 2 is to iteratively divide the number by 2 until it reaches 1. If the number is a power of 2, it’ll result in 1 after a finite number of divisions. Let’s see how this technique is implemented:

boolean isPowerOfTwoUsingLoopDivision(int n) {
    while (n != 1 && n % 2 == 0) {
        n /= 2;
    }
    return n == 1;
}

In this method, we use a while loop to divide the number by 2 until it becomes 1. If the number is a power of 2, then it’ll be divided only a few times before it becomes 1. However, for the number that is not a power of 2, the loop will keep dividing until it encounters an odd number:

assertTrue(isPowerOfTwoUsingLoopDivision(256));
assertFalse(isPowerOfTwoUsingLoopDivision(100));
By repeatedly halving the number until it reaches 1, we determine if it is a power of 2. This approach is straightforward, but it may introduce complexity and inefficiency, particularly for larger numbers, due to repeated divisions.

3. Using Bitwise & Operations

A more efficient method involves leveraging bitwise operations. In binary representation, a power of 2 has only one set bit (1) and all other bits set to 0. This characteristic allows us to exploit bitwise operators for a faster solution. Let’s implement this technique:

boolean isPowerOfTwoUsingBitwiseOperation(int n) {
    return (n != 0) && ((n & (n - 1)) == 0);
}

This method first checks if n is not zero (since zero isn’t a power of 2). Then, it uses the bitwise AND operator (&) to perform a clever trick. The expression n & (n – 1) essentially turns off the least significant set bit in n. If n was a power of 2 with only one set bit, this operation would result in zero. This is because both numbers will have their single set bits at different positions, leading to a 0 after the AND operation:

assertTrue(isPowerOfTwoUsingBitwiseOperation(256));
assertFalse(isPowerOfTwoUsingBitwiseOperation(100));

This approach is fast and efficient due to its simplicity and by leveraging a bitwise operation. However, it might be less intuitive for beginners and require a basic understanding of bitwise operations.

4. Counting Set Bits

This method involves counting the number of set bits (1s) in the binary representation of the number. Since a power of 2 has only one set bit, counting the set bits can reveal if the number is a power of 2. Here’s an example implementation:

boolean isPowerOfTwoUsingSetBitCount(int n) {
    int count = 0;
    while (n > 0) {
        count += n & 1;
        n >>= 1;
    }
    return count == 1;
}

This approach iterates through each bit of n to check if it’s set (1) using the bitwise AND with 1 (n & 1). It then accumulates the count of set bits. Next, we shift the bits of n to the right by one position using the right shift operator (>>). This operation effectively moves to the next bit in the binary representation of n.

After processing all bits, it checks if the count is equal to 1, indicating a power of 2:

assertTrue(isPowerOfTwoUsingSetBitCount(256));
assertFalse(isPowerOfTwoUsingSetBitCount(100));

This method might be useful in scenarios where counting set bits is required for other purposes.

5. Using Integer.highestOneBit()

Java provides a built-in method Integer.highestOneBit(int) that returns the integer with the highest bit set (leftmost 1) to 1 and all lower bits set to 0. Let’s see how we can leverage this method:

boolean isPowerOfTwoUsingHighestOneBit(int n) {
    return n > 0 && (n == Integer.highestOneBit(n));
}

This method ensures n is positive and compares n with the result of Integer.highestOneBit(). If n is a power of 2, it’ll have only one set bit, and both values will be equal:

assertTrue(isPowerOfTwoUsingHighestOneBit(256));
assertFalse(isPowerOfTwoUsingHighestOneBit(100));

By ensuring the number is positive and comparing it with its highest set bit, this approach offers a concise solution. However, it might entail slightly more overhead compared to bitwise operations.

6. Using Logarithm

Lastly, we can use the logarithm base 2 to check the power of 2. The base-2 logarithm of a number is the exponent to which 2 must be raised to get that number. If the logarithm (base 2) of a number is a whole number, then the number is a power of 2. Here’s the Java code demonstrating this method:

boolean isPowerOfTwoUsingLogarithm(int n) {
    return (Math.log(n) / Math.log(2)) % 1 == 0;
}

In this method, we divide the natural logarithm of n by the natural logarithm of 2 Math.log(2). If the result is a whole number, then the number is a power of 2. We use the modulo operator % to check if the result is a whole number. If the result is 0, then the number is a power of 2:

assertTrue(isPowerOfTwoUsingLogarithm(256));
assertFalse(isPowerOfTwoUsingLogarithm(100));

The advantage of this method is that it is easy to understand and implement. However, it can be slower for large numbers.

7. Summary

Each approach has its advantages and considerations. Here’s a summary.

Method Advantages Disadvantages
Loop Division Straightforward concept. Inefficient for larger numbers due to repeated divisions.
Bitwise AND Efficient and fast due to bitwise operations. Can be less intuitive for beginners.
Counting Set Bits Useful when counting set bits is required for other purposes. More complex than bitwise AND.
highestOneBit() Concise and readable code. Might have slightly more overhead.
Logarithm Easy to understand and implement. Slower for large numbers.

8. Conclusion

In this article, we’ve explored a few ways to determine if a number is a power of 2 in Java. For most applications, bitwise operations are the most efficient and effective method.

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)
1 Comment
Oldest
Newest
Inline Feedbacks
View all comments