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

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

In this tutorial, we’ll learn four approaches to check if all variables of an object are null.

2. Why Check if Variables Are Null

The null value in Java means the absence of a variable’s value. Technically, a variable containing null doesn’t point to any position in memory or wasn’t initialized yet. That can only occur with instance variables. Primitive variables such as int, double, and boolean can’t hold null.

Checking for null variables in our programs is helpful to avoid unexpected errors like IllegalArgumentException or a NullPointerException. When we try to access any member (field or method) of a null object, Java throws a NullPointerException.

One common scenario is instantiating a new object containing nested objects. The nested object is not initialized automatically. Thus, if we try to access the members of that nested object, we’ll get an unexpected error at runtime. To avoid scenarios like that, we can check if all variables in a class are null before using its members.

To exemplify, we’ll use the Car class defined below:

public class Car {
    Integer power;
    Integer year;
}

3. Using if  Statements

The simplest way is using a sequence of if statements to check field by field if they are null or not and, in the end, return a combination of their results. Let’s define the allNull() method inside the Car class:

public boolean allNull() {     
    if (power != null) {
        return false;
    }
        
    if (year != null) {
        return false;
    }
        
    return true;
}

The method defined above works just fine, as shown in the test below:

@Test
public void givenNullFields_whenCheckForNullsUsingIfs_thenReturnCorrectValue(){
    Car car = new Car();
    boolean result = car.allNull();
    assertTrue(result);
}

Although simple, this approach can be considered a code smell because we need to add a new if statement for each new field in our class. This might look effortless at first, but imagine an application with dozens of classes that contain dozens of fields. In that case, we need to write a method that validates every field for each class. That’s not very maintainable. Use this approach only if you have small classes that are less likely to change over time.

4. Using the Stream Class

We can refine the if statement solution to something more declarative using the Stream API. For example, instead of having a boolean clause for every field in our class, we can use the Stream’s allMatch() and Objects’s isNull() methods together. Let’s see how it works by creating another method in the Car class like the following:

public boolean allNullV2() {
    return Stream.of(power, year)
      .allMatch(Objects::isNull);
}

That solution also works fine, as demonstrated in the following unit test:

@Test
public void givenNullFields_whenCheckForNullsUsingStreams_thenReturnCorrectValue(){
    Car car = new Car();
    boolean result = car.allNullV2();
    assertTrue(result);
}

The allNullV2() is the declarative version of allNull(). It makes the code more extensible since we need to add only the field name in the Stream instead of an entire if statement.

5. Using ObjectUtils from Apache Commons

Another option is to use the utility class ObjectUtils from the Apache commons-lang3 libraryThe ObjectUtils’s allNull() method has a generic API that handles any type and number of parameters. That method receives an array of Objects and returns true if all values in that array are null. Otherwise, return false. Let’s first add the latest version of the commons-lang3 dependency to our pom.xml file:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Now, let’s see how the allNull() method works in the following unit test:

@Test
public void givenNullFields_whenCheckForNullsUsingApacheCommons_thenReturnCorrectValue(){
    Car car = new Car();      
    boolean result = ObjectUtils.allNull(car.power, car.year);
    assertTrue(result);
}

That approach uses an external dependency to achieve the same result. So, we must consider if it’s worth pulling an entire dependency for such a simple task. Similar to the Stream approach, the good thing about allNull() is that it receives an array of Objects, creating a generic API. Thus, that works with any type and number of fields in our class. However, we still need to pass newly added class fields as arguments for the allNull() method.

We’ll see in the next section that, using the Reflection API, we can avoid modifying our null checker whenever we add more variables to our model class.

6. Using the Reflection API

Since all fields inherit the Object class, we can create a generic method that works with any type except primitives. To do that, we can access all fields of an Object’s instance in runtime and search for nulls using the Reflection API. Let’s create a new class named NullChecker with the content below:

public class NullChecker {

    public static boolean allNull(Object target) {
        return Arrays.stream(target.getClass()
          .getDeclaredFields())
          .peek(f -> f.setAccessible(true))
          .map(f -> getFieldValue(f, target))
          .allMatch(Objects::isNull);
    }

    private static Object getFieldValue(Field field, Object target) {
        try {
            return field.get(target);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}

This version is slightly more complicated than the previous ones, so let’s analyze that code in parts:

  • The allNull() method defines a Stream of the target Object’s declared fields using the getClass() and getDeclaredFields() methods. In our example, that Stream consists of power and year fields
  • The peek() operation makes all private fields (if any) accessible from outside the class using the setAcessible(true) method
  • Then, we map() the class fields to their values using the helper method getFieldValue(), which catches the checked exception thrown by the get() method of the Field class
  • Finally, we check if all class fields values are null using allMatch()

Let’s validate if that works using a unit test:

@Test
public void givenNullFields_whenCheckForNullsUsingReflection_thenReturnCorrectValue() {
    Car car = new Car();
    boolean result = NullChecker.allNull(car);
    assertTrue(result);
}

That API is generic in its contract and works with any class we define. However, the Reflection API has the pitfall of being more dangerous than the other approaches because we don’t need any prior knowledge about our null checker at compile time, which makes bugs harder to find. Another problem with Reflection is that it is usually slower than other approaches since there’s much more work to be done at runtime.

7. Conclusion

In this article, we’ve seen the importance of checking for null variables in our classes and how to do that using if statements, Streams, the Apache commons-lang3 library, and the Reflection API.

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)