Understanding the Nuances: Difference Between @NotNull and @Nonnull in Java

Naveen Metta
5 min readOct 21, 2024
credit goes to the owner : https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrVDxjLGqaOI&psig=AOvVaw1YwnWJGvC2hIMSViDrr8L7&ust=1729564976519000&source=images&cd=vfe&opi=89978449&ved=0CBcQjhxqFwoTCLCt6OW5nokDFQAAAAAdAAAAABAE
source: youtube.com

When working with Java, especially in projects where object-oriented principles are at the core, the concept of nullability is fundamental. Null references can cause NullPointerExceptions, which are a common source of errors. Thankfully, Java provides annotations like @NotNull and @Nonnull that help developers prevent such problems. Though they sound alike and serve a similar purpose, it's crucial to grasp their differences to use them effectively. In this article, we'll explore the distinction between @NotNull and @Nonnull, offering clear explanations and examples to help even novice Java developers understand their use and importance.

Null Safety and its Importance

Before diving into the specifics of @NotNull and @Nonnull, let's understand why null safety is vital in Java. Imagine a simple scenario where you're trying to perform an operation on a variable that is supposed to hold an object reference. If the variable is null and you attempt to invoke a method or access a property of the supposed object, the Java runtime throws a NullPointerException, indicating that you tried to use a null reference as though it were an actual object. Such exceptions are not only disruptive but can also lead to a poor user experience and tricky bugs.

--

--

Naveen Metta
Naveen Metta

Written by Naveen Metta

I'm a Full Stack Developer with 3+ years of experience. feel free to reach out for any help : mettanaveen701@gmail.com

No responses yet