Thursday, 10 July 2025

@Nonnull versus @NotNull

A quick small blog...

So, we have two (seemingly) conflicting annotations for the same thing1.

Even people who know exactly when to use what have a chance to pick the wrong one, especially with the use of Code Completion and AI nowadays.

So here's a quick rundown, but the reference below is much more in depth:

import javax.annotation.Nonnull;

@Nonnull
IDEs and Compilers use it for Static Analysis of code. (Though the RetentionPolicy is set to RUNTIME)
import jakarta.validation.constraints.NotNull;

@NotNull
Validation Frameworks (like ORMs) use it during Runtime for checks.

What about Nullable values?

import javax.annotation.Nullable;

@Nullable
IDEs and Compilers use it for Static Analysis of code.

There is no @Nullable available for jakarta.validation.constraints. By default things are nullable, unless explicitly mentioned otherwise.

When not to use @NotNull

The primary really important thing to take away from this is to not do the following:

It might work, your IDE might complain or it might not, but at runtime this will be ignored, unless this method is called by a Framework as mentioned above.

Addendum

Don't use javax.validation.constraints.NotNull. It's been superseded by Jakarta when Oracle moved Java EE to Jakarta. See [2].

Referenties

[1] Medium - Understanding @NotNull vs @Nonnull in Java: A Practical Guide to Null-Safety
https://medium.com/@mesfandiari77/understanding-notnull-vs-nonnull-in-java-a-practical-guide-to-null-safety-5e179e918f37
[2] Medium - Difference between javax.validation and jakarta.validation
https://medium.com/@ovinduuu/difference-between-javax-validation-and-jakarta-validation-df0c6dbe5cb3

No comments:

Post a Comment