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 programming, some tasks seem deceptively simple like checking if two boolean values are equal. While this might sound trivial, there are several approaches to achieve this, each with unique implications on readability, functionality, and edge cases.

In this tutorial, we’ll explore how to check for equality between boolean values and when each method is appropriate.

2. Ways to Check Equality of Boolean Values

There are multiple ways to check for equality, each with its nuances and best-use scenarios. Understanding these methods can help us write clearer, safer, and more efficient code, especially when dealing with object references, handling null values, or integrating comparisons in more complex expressions.

In this section, we’ll explore various ways to check if two boolean values are equal.

2.1. Quick and Direct Comparison

The simplest and most intuitive way to check if two boolean values are equal is by using the == operator:

@Test
void givenPrimitiveBooleans_whenUsingDirectComparison_thenCompare() {
    boolean a = true;
    boolean b = true;
    assertTrue(a == b, 
      "Direct comparison of primitive booleans should be true when both are the same");

    a = true;
    b = false;
    assertFalse(a == b, 
      "Direct comparison of primitive booleans should be false when they differ");
}

In this example, the result will be true if both a and b have the same boolean value, and false otherwise. This works well for primitive boolean values (true or false) and is ideal when we’re sure both values are non-null and of type boolean.
Java’s == operator works naturally with primitive types, including boolean, as it checks value equality rather than reference equality. It’s also efficient, as it compares values directly. This approach is clear and performant for simple checks, making it the go-to choice for most cases.
However, the story changes when working with Boolean objects instead of primitive boolean values. This is what the next section is all about.

2.2. The equals() Method for Boolean Objects

When we’re comparing Boolean objects (Java’s wrapper class for boolean), using == might not yield the results we expect. Boolean is an object, so using == checks for reference equality rather than value equality. To ensure we’re comparing values instead of references, the equals() method is a better choice:

@Test
void givenBooleans_whenUsingEqualsMethodWithBooleanObjects_thenCompare() {
    Boolean a = Boolean.TRUE;
    Boolean b = Boolean.TRUE;
    assertTrue(a.equals(b), 
      "Using equals() on Boolean objects should be true when both values are the same");

    a = Boolean.TRUE;
    b = Boolean.FALSE;
    assertFalse(a.equals(b), 
      "Using equals() on Boolean objects should be false when values differ");
}

In this code, a.equals(b) checks if the underlying boolean values are the same, regardless of whether a and b are distinct Boolean instances.
So, why not use == with Boolean objects?

Let’s consider the following code:

@Test
void givenBooleansTypes_whenUsingDirectOperator_thenCompare() {
    Boolean a = Boolean.TRUE;
    Boolean b = new Boolean(true);
    assertFalse(a == b, 
      "Using == on different boolean objects should be false when values differ");
}

Though a and b both have the value true, using == returns false because a and b are different Boolean instances. Using equals() ensures the comparison is based on the actual value (true or false) rather than the object reference, which is particularly helpful when dealing with nullable values.
We use equals() on Boolean objects to avoid unexpected behavior caused by object reference comparison.

2.3. Using Logical XOR

We should consider using the logical XOR (exclusive OR) operator ^ for a more creative solution. XOR between two booleans returns true if the values differ and false if they’re the same.
By negating the result, we can check if the two booleans are equal:

@Test
void givenBooleans_whenUsingXORApproach_thenCompare() {
    boolean a = true;
    boolean b = true;
    assertTrue(!(a ^ b), 
      "XOR approach should return true when both values are the same");

    a = true;
    b = false;
    assertFalse(!(a ^ b), 
      "XOR approach should return false when values differ");
}

This method works by checking if both values are either true or false. While this approach is less common and slightly harder to read, it’s efficient and useful in scenarios where we might already be using XOR logic.

Using XOR can feel less intuitive, so it’s best suited for situations where XOR logic already makes sense or where performance is critical. If our code’s readability is a priority, the == operator might be a better choice.

2.4. Using Boolean.compare()

Java provides a static method called Boolean.compare() specifically for comparing two boolean values. This method returns 0 if the values are equal, 1 if the first is true and the second is false, and -1 if the first is false and the second is true:

@Test
void givenBooleans_whenUsingBooleanCompare_thenCompare() {
    boolean a = true;
    boolean b = true;
    assertTrue(Boolean.compare(a, b) == 0, 
      "Boolean.compare() should return 0 when both values are the same");

    a = true;
    b = false;
    assertFalse(Boolean.compare(a, b) == 0, 
      "Boolean.compare() should return non-zero when values differ");
}

This approach can be useful when we’re working with sorting or need more than just an equality check. By checking  Boolean.compare(a, b) == 0, we confirm that both booleans are either true or false.

2.5. Avoiding NullPointerException With Objects.equals()

If we’re comparing Boolean objects that might be null, using Objects.equals() from the java.util.Objects package is a good option. It handles null values gracefully, returning true if both are null, or false if only one of them is:

@Test
void givenBooleans_whenUsingObjectsEqualsForNullableBooleans_thenCompare() {
    Boolean a = null;
    Boolean b = null;
    assertTrue(Objects.equals(a, b), 
      "Objects.equals() should return true when both Boolean objects are null");

    a = Boolean.TRUE;
    b = null;
    assertFalse(Objects.equals(a, b), 
      "Objects.equals() should return false when one Boolean is null");

    a = Boolean.TRUE;
    b = Boolean.TRUE;
    assertTrue(Objects.equals(a, b), 
      "Objects.equals() should return true when both Boolean values are the same");

    a = Boolean.TRUE;
    b = Boolean.FALSE;
    assertFalse(Objects.equals(a, b), 
      "Objects.equals() should return false when Boolean values differ");
}

This approach avoids NullPointerException and checks value equality. It’s especially useful when dealing with nullable data or when comparing potentially uninitialized values.

3. Comparison of Approaches

Let’s have a look at a comparison for all the ways discussed.

Method Use case Notes
== Simple, direct comparison of boolean values Fast and straightforward; avoid with Boolean objects
equals() Boolean object comparison Preferred for non-primitive types to avoid reference equality issues
XOR (^) Creative option, uncommon Efficient but less readable; use if XOR logic is suitable
Boolean.compare() Detailed comparison or sorting needs Returns 0 for equality; useful in sorting
Objects.equals() Handling potential null values Safely handles nullable Boolean objects

4. Conclusion

In this article, we saw that checking for the equality between boolean values can be simple yet varied, with each approach offering unique advantages. For basic, direct comparisons, == works best with primitive types, while equals() ensures reliable results with Boolean objects. Methods like XOR, Boolean.compare(), and Objects.equals() add flexibility for specialized needs, such as handling nulls or integrating comparisons in complex logic.

Choosing the right approach helps make our code more readable, safe, and tailored to our specific requirements, ensuring clarity and correctness in boolean comparisons.

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