Method 4 is best.

if(foo != null && foo.bar()) {
   someStuff();
}

will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.

Answer from Jared Nielsen on Stack Overflow
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › validation › constraints › NotNull.html
NotNull (Java(TM) EE 7 Specification APIs)
javax.validation.constraints · @Target(value={METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER}) @Retention(value=RUNTIME) @Documented @Constraint(validatedBy={}) public @interface NotNull · The annotated element must not be null. Accepts any type. Author: Emmanuel Bernard ·
🌐
Medium
medium.com › @mesfandiari77 › understanding-notnull-vs-nonnull-in-java-a-practical-guide-to-null-safety-5e179e918f37
Understanding @NotNull vs @Nonnull in Java: A Practical Guide to Null-Safety | by MEsfandiari | Medium
February 13, 2025 - @NotNull is an annotation that indicates a variable, parameter, or return value cannot be null. It is widely used in Java development and is supported by multiple libraries, including:
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
April 8, 2019 - This makes it explicit to the client ... null or not. ... Here, @NonNull makes it clear that the argument cannot be null. If the client code calls this method without checking the argument for null, FindBugs would generate a warning at compile time.
🌐
Educative
educative.io › answers › what-is-validatenotnull-in-java
What is Validate.notNull in Java?
the methods in Java that can be called without creating an object of the class. method of the Validate class that is used to check whether the passed object is null or not.
🌐
Project Lombok
projectlombok.org › features › NonNull
@NonNull
The conditional of the if statement must look exactly like PARAMNAME == null; the assert statement must look exactly like PARAMNAME != null. The invocation to a requireNonNull-style method must be on its own (a statement which just invokes that method), or must be the expression of an assignment or variable declaration statement. The first statement in your method that is not such a null-check stops the process of inspecting for null-checks.
🌐
Educative
educative.io › answers › what-is-objectsnonnull-in-java
What is Objects.nonNull in Java?
The nonNull method is a static method of the Objects class in Java that checks whether the input object reference supplied to it is non-null or not.
🌐
Sonar Community
community.sonarsource.com › sonarqube for ide › vs code
Declaring a non-null return value? - VS Code - Sonar Community
June 18, 2021 - Using VS Code and Java, I’m trying to set up a class that receives potentially null values, and verifies they are not null as part of instance construction. Here’s a simplified version (the real code uses a builder pattern). public class Job { private @NonNull String name; public Job(@Nullable String jobName) { this.name = checkNotNull(jobName, "Name cannot be null"); } } My checkNotNull() is… public static @NonNull T checkNotNull(@Nullable T value, @NonNull String message...
Find elsewhere
🌐
Openjml
openjml.org › tutorial › Nullness
JML Tutorial - Nullable and non-null values and types
Accordingly, when ss is initialized or the target of an assignment, the value it is given must be provably not null. But thereafter the values can be assumed to be non-null. If there is no modifier, the default is non-null. Instead of these modifiers, one can use the Java annotations @NonNull ...
🌐
Baeldung
baeldung.com › home › spring › spring boot › using @notnull on a method parameter
Using @NotNull on a Method Parameter | Baeldung
May 11, 2024 - By using @NotNull, we indicate that we must never call our method with a null if we want to avoid an exception. However, by itself, that’s not enough.
🌐
Coderanch
coderanch.com › t › 496486 › java › null-null-java
null and not null in java (Beginning Java forum at Coderanch)
Dear Sir, Null fields in a database (bad design practice).Specifiying a field as NOT NULL means when you insert a new record you will always have a value to fill that column. It allows the database system to optermise your database and as NOT NULL are used for primary keys for the database,but ...
🌐
Better Programming
betterprogramming.pub › checking-for-nulls-in-java-minimize-using-if-else-edae27016474
Checking for Nulls in Java? Minimize Using “If Else” | by Itır ...
January 26, 2022 - Lets say that you have Student.javawith fields such as id, name and classes. You can use put @Builder.Default before the related field and give it a default value. When an instance of this Student class is created, it will have “classes” as an empty list, not null.
🌐
Medium
medium.com › javarevisited › avoid-verbose-null-checks-b3f11afbfcc9
Avoid Explicit Null Checks. One of the more frustrating things… | by JAVING | Javarevisited | Medium
February 3, 2022 - The client will be able to choose to pass a null object instead of a null, and this will avoid having to do an explicit null check in method(). Optional Latest versions of java have a class called Optional that can be used as a way of avoiding ...
🌐
Blogger
javarevisited.blogspot.com › 2016 › 01 › how-to-check-if-string-is-not-null-and-empty-in-java-example.html
How to check if String is not null and empty in Java? Example
Since we are first doing a null check and then an empty check using the && operator, which is a short circuit AND operator. This operator will not check for emptiness if String is null hence no NPE. This is also a good trick to avoid NPE in Java.
🌐
DZone
dzone.com › coding › languages › why i never null-check parameters
Why I Never Null-Check Parameters
December 4, 2018 - In a perfect world, it should not be possible to pass or return null values, at least not in public methods. This is one area where Kotlin, Haskell, and others are clearly better designed than Java. We can, however, pretend that nulls don't exist.
🌐
Medium
medium.com › javarevisited › difference-between-notnull-and-nonnull-in-java-dde9823c3879
Difference Between @NotNull and @Nonnull in Java | by Sergio Sánchez | Javarevisited | Medium
August 18, 2024 - The `@NotNull` annotation is widely used in Java for validation purposes. When you apply this annotation to a field, parameter, or method return value, you’re indicating that it must never be `null`. This is particularly important when you’re ...
Top answer
1 of 3
5

The dilemma

If a variable with null value gets used in your program causing a NullPointerException, this is clearly a situation in your program which you did not expect. You must ask yourself the question: "Did I not expect it because I didn't take into consideration the possibility of a null value or did I assume the value could never be null here?"

If the answer is the latter, the problem isn't because you didn't handle the null value. The problem happened earlier, and you're only seeing the consequence of that error on the particular line it's used. In this case, simply adding a if (variable != null) isn't going to cut it. You'll wind up skipping lines you were supposed to execute because the variable was null, and you'll ultimately hit a line further on where you again assumed it wouldn't be null.

When null should be used

As a general rule, return null only when "absent" is a possible return value. In other words, your data layer may search for a record with a specific id. If that record isn't found, you can either throw an exception or simply return null. You may do either, but I prefer not to throw exceptions in situations where the strong possibility exists. So you return null instead of a value.

The caller of this method, presumably written by you, knows the possibility exists that the record may not exist and checks for null accordingly. There is nothing wrong with this in this case, though you should handle this possibility as soon as possible as otherwise everywhere in your program you will need to deal with the possibility of a null value.

Conclusion

In other words, treat null as a legitimate value, but deal with it immediately rather than wait. Ideally in your program, you should ever only have to check if it is null once in your program and only in the place where such a null value is handled.

For every value you expect to be non-null, you need not add a check. If it is null, accept that there is an error in your program when it was instantiated. In essence, favor fail fast over fail safe.

2 of 3
8

Deciding whether or not null is a allowed as an object value is a decision that you must make consciously for your project.

You don't have to accept a language construct just because it exists; in fact, it is often better to enforce a strict rule against any nullvalues in the entire project. If you do this, you don't need checks; if a NullPointerException ever happens, that automatically means that there is a defect in your code, and it doesn't matter whether this is signalled by a NPE or by some other sanity check mechanism.

If you can't do this, for instance because you have to interoperate with other libraries that allow null, then you do have to check for it. Even then it makes sense to keep the areas of code where null is possible small if possible. The larger the project, the more sense it makes to define an entire "anti-corruption layer" with the only purpose of preserving stricter value guarantees than is possible elsewhere.