What @Nullable to use in Java (as of 2023/JDK21)? – Java

by
Ali Hasan
java-21 nullable

Quick Fix: Integrate the jakarta.annotation.Nullable annotation from the jakarta.annotation-api library into your Java codebase as it is currently the most widely adopted and recommended option for indicating nullability in Java.

The Solutions:

Solution 1: jakarta.annotation.Nullable

The `jakarta.annotation.Nullable` annotation from the `jakarta.annotation-api` library is considered the closest to being the standard for nullable annotations in Java as of 2023 and JDK 21.

The earlier `javax.annotation.Nullable` annotation is now linked to the `jakarta.annotation-api` library and will be handled by popular tools like the checker framework.

While `javax.annotation.Nullable` is still widely used, it is recommended to migrate to `jakarta.annotation.Nullable` for future-proofing, as more projects adopt the newer Java Servlet versions.

Use the following import statement to access `jakarta.annotation.Nullable`:

import jakarta.annotation.Nullable;

Solution 2: Checker Framework

The Checker Framework provides @Nullable and @NonNull annotations, which are the most widely recognized and utilized nullness annotations in Java.

These annotations offer several benefits:

  • Precise documentation: They clearly indicate the nullness properties of variables and method parameters.
  • Tool verification: Tools like the Nullness Checker and NullAway can verify or heuristically check the validity of this documentation.
  • Test framework integration: Some automated test frameworks consider these annotations when generating tests.

It’s important to note that no official Oracle-approved @Nullable annotation exists. javax.annotation.Nullable was introduced by FindBugs, but it violates Oracle’s licensing terms and is not endorsed.

Solution 3: _jspecify_

_jspecify_ is a tool-independent nullness annotation standard created by a group led by Google. It offers a consensus-based, precisely defined, and less strict annotation compared to other options. _jspecify_ aims to be less complex, easier to migrate, and provide more accurate results than existing tools.

Q&A

What @Nullable to use in Java (as of 2023/JDK21)?

jakarta.annotation.Nullable from the jakarta.annotation-api.

What @Nullable to use in Java (as of 2023/JDK21)?

org.checkerframework.checker.nullness.qual.Nullable from the Checker Framework.

What @Nullable to use in Java (as of 2023/JDK21)?

jspecify, a new group-developed standard.