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

One of the common sources of frustration for Java developers is the NullPointerException. Be it working in large code bases or making an API call, Java developers always had to question themselves, “What if this returns null?” and how to handle it. Despite Java being a statically typed language, its handling of null values has always left room for ambiguity.

In the recent past, the Java Community has taken steps towards addressing this very issue. One of the promising developments in this area is JSpecify.

In this tutorial, let’s explore what JSpecify is and how we can implement it in our projects.

2. What Is JSpecify?

Jspecify provides a standard set of annotations to explicitly declare the nullness expectations of the Java code. Jspecify is tool-agnostic, meaning it’s not tied to any specific framework or IDE. It works across the entire Java ecosystem.

It allows developers to annotate if a method, field, or parameter (including generic parameters) can hold a null value or not. This helps IDEs, static analysis tools, and compilers catch potential null-related issues during development.

While there were annotations for null checks in the past, the problem was that different projects and tools often used different annotations with slightly varying meanings. JSpecify, however, seeks to unify these efforts under one precise, consistent, and interoperable standard.

3. Why Care About Null Safety?

Historically, Java relied on implicit nullability, where variables are assumed to be nullable or non-nullable based on default behavior or context, without the developer explicitly specifying it every time.

If the tools are aware of the null expectations, they can warn us when we violate them. This helps us catch bugs early in the development process.

Also, when we explicitly specify nullability, consumers of our API immediately understand whether a method can return null or whether a parameter can accept null. Their IDE shows nullability information as hints or warnings.

4. How to Use JSpecify

JSpecify allows us to specify various annotations to express nullness.

To start using Jspecify, we need to add the following dependency:

<dependency>
    <groupId>org.jspecify</groupId>
    <artifactId>jspecify</artifactId>
    <version>1.0.0</version>
</dependency>

JSpecify offer various annotations to express nullness.

The @Nullable annotation means that the annotated element may legally be null. @NonNull means that the annotated element must never be null.

We can also specify nullness at the package or class level. For example, the @NullMarked annotation is applied to a package, class, or module to indicate that, by default, all unannotated types are considered non-null.

Similarly, we have @NullUnmarked annotation, which cancels the effect of @NullMarked and allows unannotated types to have unspecified nullness.

These annotations provide flexibility. For example, we can make everything non-null by default by using @NullMarked and only explicitly annotate places where null is acceptable with @Nullable. This way, we can reduce the number of annotations required.

Once we add the dependency, we can start using the annotations in our code as follows:

@Nullable
private String findNicknameOrNull(String userId) {
    if ("user123".equals(userId)) {
        return "CoolUser";
    } else {
        return null;
    }
}
@Test
void givenUnknownUserId_whenFindNicknameOrNull_thenReturnsNull() {
    String nickname = findNicknameOrNull("unknownUser");
    assertNull(nickname);
}

@Test
void givenNullableMethodResult_whenWrappedInOptional_thenHandledSafely() {
    String nickname = findNicknameOrNull("unknownUser");
    Optional<String> safeNickname = Optional.ofNullable(nickname);

    assertTrue(safeNickname.isEmpty());
}

In the above code, the method findNicknameOrNull(String userId) is annotated with @Nullable, which signals to the developer that it might return null. This helps catch potential null-related issues at compile time. However, since JSpecify has no effect during runtime, the test here verifies the expected runtime behavior where the method indeed returns null when the user is not found.

In the second test, though, we’re using Optional to safely encapsulate the null value, thereby eliminating the risk of a NullPointerException.

5. Comparison with Other Null-Checking Approaches

Before JSpecify, we had other approaches to check for nullability. In this section, we’ll explore various ways to write null-safe code.

5.1. Using Optional

java.util.Optional is a container object that wraps the return value that either contains a non-null value or signifies absence. It provides a type-safe and explicit way to handle the potential absence of a value, thereby reducing the risk of a NullPointerException. Optional forces the caller of the method to consciously handle both scenarios.

For example, let’s take a look at the code below:

private Optional<String> findNickname(String userId) {
    if ("user123".equals(userId)) {
        return Optional.of("CoolUser");
    } else {
        return Optional.empty();
    }
}

The method never returns null. It always returns an Optional. Either Optional.of(value) when there is a value. Optional.empty() when there isn’t a value.

Now, let’s take a look at how we deal with Optional from the calling method:

@Test
void givenKnownUserId_whenFindNickname_thenReturnsOptionalWithValue() {
    Optional<String> nickname = findNickname("user123");

    assertTrue(nickname.isPresent());
    assertEquals("CoolUser", nickname.get());
}

@Test
void givenUnknownUserId_whenFindNickname_thenReturnsEmptyOptional() {
    Optional<String> nickname = findNickname("unknownUser");

    assertTrue(nickname.isEmpty());
}

We can see from the above code that the caller will either receive the Optional with a value or an empty Optional and must handle presence or absence explicitly, which reduces the risk of getting a NullPointerException.

However, Optional is primarily intended for method return types and not for fields or method parameters. Using Optional for fields or method parameters would introduce additional complexity.

Also, Optional introduces a small performance cost due to object creation and wrapping.

5.2. Using Objects.requireNonNull()

Another common practice for handling potential null-related issues is by using runtime assertions, using Objects.requireNonNull. This method throws a NullPointerException immediately if the provided argument is null.

For example, let’s take a look at this code:

@Test
void givenNonNullArgument_whenValidate_thenDoesNotThrowException() {
    String result = processNickname("CoolUser");
    assertEquals("Processed: CoolUser", result);
}

@Test
void givenNullArgument_whenValidate_thenThrowsNullPointerException() {
    assertThrows(NullPointerException.class, () -> processNickname(null));
}

private String processNickname(String nickname) {
    Objects.requireNonNull(nickname, "Nickname must not be null");
    return "Processed: " + nickname;
}

As we can see from the above code, if the argument is null, a NullPointerException is thrown immediately. It makes bugs more visible during testing as they fail early instead of silently flowing into deeper logic.

By validating the inputs right at the beginning of a method, we can catch violations during development or testing; this will prevent errors during production.

However, one key limitation of requireNonNull() is that it only detects problems during runtime. They do not provide compile-time or IDE hints like JSpecify.

6. JSpecify Adoption Strategy

It’s impractical to annotate the entire codebase in one go. Thankfully, JSpecify allows gradual adoption. We can incrementally implement null safety annotations without breaking the code.

A typical adoption strategy is to start annotating small, self-contained packages or classes and then use @NullMarked to enforce non-null defaults, reducing annotation noise. We can then explicitly add @Nullable annotations wherever necessary.

We can also run static analysis tools to catch any mismatches and refine our annotations, and then gradually expand coverage to broader parts of the codebase.

7. Tooling and Ecosystem Support

Many of the popular tools and IDEs now support JSpecify annotations to varying degrees.

For example, Checker Framework, which is a popular static analysis tool, has its own annotations for null safety; however, it has started supporting JSpecify’s core annotations in recent versions.

Similarly, NullAway is yet another static analysis tool focused on detecting nullability issues. It now supports JSpecify annotations.

From the IDE’s front, IntelliJ IDEA has long been supporting nullness annotations, including its own. IntelliJ now offers basic recognition of JSpecify annotations, highlighting mismatches and potential nullability problems.

8. Conclusion

In this article, we discussed the JSpecify tool that helps developers get rid of null-related errors to a great degree. It certainly makes the Java codebase more robust and resilient, with fewer surprises during production. While tooling support is still maturing, the momentum behind JSpecify suggests it will soon become the default approach for expressing nullness 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.

Course – LS – NPI (cat=Java)
announcement - icon

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

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
4 Comments
Oldest
Newest
Inline Feedbacks
View all comments