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
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
April 8, 2019 - Learn several strategies for avoiding the all-too-familiar boilerplate conditional statements to check for null values in Java.
🌐
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 - Null checks are bad but returning null is also equally bad. There are many things the called function could do to avoid returning null. If the exception appears this will at least prompt a conversation about if something is mandatory, why is not present? Perhaps more thought about system design is required. Using assertions The java keyword ‘assert’ can be used in combination with a boolean expression to stop the program execution by throwing an assertion error.
🌐
DEV Community
dev.to › scottshipp › better-null-checking-in-java-ngk
Better Null-Checking in Java - DEV Community
January 11, 2019 - A NullPointerException is thrown whenever the JVM attempts to dereference a variable and finds null instead of an object. How can you prevent that? The answer is easy: just don’t have any variables pointing to null. Unfortunately, Java is a nasty language that practically forces the programmer into creating (or receiving through method parameters) variables referencing null.
🌐
DZone
dzone.com › data engineering › databases › 10 tips to handle null effectively
10 Tips to Handle Null Effectively
January 26, 2017 - Handling nulls can be a complicated problem on its own and therefore we should make it as clean and as obvious as possible. One very bad practice that I’ve seen in some codebases is using Objects methods, Optional classes, or even a separate method using Optional in places where a simple null check would be enough.
Top answer
1 of 11
47

If null is a reasonable input parameter for your method, fix the method. If not, fix the caller. "Reasonable" is a flexible term, so I propose the following test: How should the method hande a null input? If you find more than one possible answer, then null is not a reasonable input.

2 of 11
22

Don't use null, use Optional

As you've pointed out, one of the biggest problems with null in Java is that it can be used everywhere, or at least for all reference types.

It's impossible to tell that could be null and what couldn't be.

Java 8 introduces a much better pattern: Optional.

And example from Oracle:

String version = "UNKNOWN";
if(computer != null) {
  Soundcard soundcard = computer.getSoundcard();
  if(soundcard != null) {
    USB usb = soundcard.getUSB();
    if(usb != null) {
      version = usb.getVersion();
    }
  }
}

If each of these may or may not return a successful value, you can change the APIs to Optionals:

String name = computer.flatMap(Computer::getSoundcard)
    .flatMap(Soundcard::getUSB)
    .map(USB::getVersion)
    .orElse("UNKNOWN");

By explicitly encoding optionality in the type, your interfaces will be much better, and your code will be cleaner.

If you are not using Java 8, you can look at com.google.common.base.Optional in Google Guava.

A good explanation by the Guava team: https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained

A more general explanation of disadvantages to null, with examples from several languages: https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/


@Nonnull, @Nullable

Java 8 adds these annotation to help code checking tools like IDEs catch problems. They're fairly limited in their effectiveness.


Check when it makes sense

Don't write 50% of your code checking null, particularly if there is nothing sensible your code can do with a null value.

On the other hand, if null could be used and mean something, make sure to use it.


Ultimately, you obviously can't remove null from Java. I strongly recommend substituting the Optional abstraction whenever possible, and checking null those other times that you can do something reasonable about it.

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.

Find elsewhere
Top answer
1 of 4
8

It is a good idea to check for null explicitly because:

  • You can catch the error earlier.
  • You can provide a more descriptive error message.

If you get a NullPointerException you might not be able to work out exactly which variable was null. Even if you have the line number where the exception was thrown, there might still be more than one variable on that line.

It's particularly important to put these checks in your public interface. This is because when your user provides an incorrect parameter they should get an IllegalArgumentException telling them that they made an error. If they just get back a NullPointerException they can't tell if they provided an incorrect parameter, or if there is just a bug in your code.

2 of 4
3

Here are some of the best practices in the order of importance:

  1. Don't return a null if you can help it. For example, if your method returns a collection, return an empty collection rather than a null. In some instances the Null Object pattern can be of help. But you have to be careful to only use it where the NullObject can offer a reasonable default behavior without an additional if-check.
  2. Check for nulls if your code can offer a reasonable handling of null cases. If you simply throw another exception upon detecting a null, there is little value in handling the null explicitly.
  3. Document all instances of a function returning nulls in the function's javadoc. (unfortunately, you can't really rely on the javadoc, but it help in maintaining discipline).
🌐
Coderanch
coderanch.com › t › 776220 › java › null-check-method-parameters-Java
When should you null check method parameters in Java? (Beginning Java forum at Coderanch)
Additionally, null checks should ... if using try catch or throw new WhateverException. It is also best practice to null check and validate parameters in both public and private methods....
🌐
Mezo Code
mezocode.com › home › handling null in java: 10 pro strategies for expert developers
Handling Null in Java: 10 Pro Strategies for Expert Developers | Mezo Code
October 16, 2024 - When to use: Optional is best used ... you express a variable that might be null more explicitly: 🔴 Avoid Practice: Using Optional as a method ......
🌐
Coderanch
coderanch.com › t › 649288 › java › Null-check-good-practice-variables
Null check good practice for several variables (Beginning Java forum at Coderanch)
Winston Gutkowski wrote: . . . If I call a 3rd party method that doesn't document when (or that) it throws an NPE, I will always check the arguments I pass myself - possibly redundantly - so good documentation is really important. . . . Fail fast and fail early? Also declare fast and declare early. It took me a long time to realise that methods like this throw an NPE if you pass null, but the link doesn't tell you that. This method introduced in Java8 does however say, “throws NullPointerException if …” I find that confusing, and the fact that you scroll up and then read this
🌐
Deep Java
java.digibeatrix.com › home › data handling & collections (java standard library) › java null checks explained: best practices, common pitfalls, and modern solutions
Java Null Checks Explained: Best Practices, Common Pitfalls, and Modern Solutions - Deep Java
December 29, 2025 - Even in Java 17 and later, API ... current best practice in Java is to assume that null can exist and to write defensive code using Optional, the Null Object pattern, and utility classes....
🌐
Quora
quora.com › What-are-the-best-practices-for-managing-null-value-effectively-in-Java
What are the best practices for managing null value effectively in Java? - Quora
Answer (1 of 3): The billion dollar mistake is quite interesting to deal with. One philosophy says that null is a valid value, which is fine for a more primitive object like a String or an Integer, but becomes rather messy if you ever have to call a method on said null object. In that scenario of...
🌐
Oracle
oracle.com › java › technical details
Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!
Scala has a similar construct called Option[T] to encapsulate the presence or absence of a value of type T. You then have to explicitly check whether a value is present or not using operations available on the Option type, which enforces the idea of "null checking." You can no longer "forget to do it" because it is enforced by the type system. OK, we diverged a bit and all this sounds fairly abstract. You might now wonder, "so, what about Java SE 8?"
🌐
DZone
dzone.com › coding › languages › why i never null-check parameters
Why I Never Null-Check Parameters
December 4, 2018 - Methods and constructors should not check for nulls ... Constructors with multiple parameters that aren't required should consider using the Builder Pattern. Methods that returned null should return Optional or a special implementation of whatever ...
🌐
Blogger
javarevisited.blogspot.com › 2013 › 05 › ava-tips-and-best-practices-to-avoid-nullpointerexception-program-application.html
Java Tips and Best practices to avoid NullPointerException in Java Applications
... Anonymous said... The best practice I think is to consider null references as actual errors. Using null references for program flow should be avoided, and null checks should almost only be necessary for inputs from outside the system.
🌐
Winterbe
winterbe.com › posts › 2015 › 03 › 15 › avoid-null-checks-in-java
Avoiding Null Checks in Java 8 - winterbe
We can get rid of all those null checks by utilizing the Java 8 Optional type. The method map accepts a lambda expression of type Function and automatically wraps each function result into an Optional. That enables us to pipe multiple map operations in a row.