Method 4 is best.

Copyif(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
February 20, 2026 - This makes it explicit to the client code whether the annotated type can be 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. Developers generally rely on IDEs for writing Java code.
Discussions

java - How to check a string is not null? - Stack Overflow
Checks if a CharSequence is empty (""), null or whitespace only. ... You should specify its library full name, Commons, and be more specific on the method behaviour. Imho, you should improve the answer a bit. Regards 2018-05-26T08:17:56.98Z+00:00 ... Predicate notNull = Predicate.n... More on stackoverflow.com
🌐 stackoverflow.com
nullpointerexception - How do I avoid checking for nulls in Java? - Stack Overflow
This is the approach the Java library takes; favoring NullPointerException over IllegalArgumentException when an argument is not allowed to be null. (1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it. More on stackoverflow.com
🌐 stackoverflow.com
December 5, 2020
Null safety
I'm coming back to Java after almost 10 years away programming largely in Haskell. I'm wondering how folks are checking their null-safety. Do folks use CheckerFramework, JSpecify, NullAway, or what? Archived post. New comments cannot be posted and votes cannot be cast. Share ... Yeah.. My workplace has similarly outlawed nulls (mostly). We have compile-time jspecify framework to require explicit @ Nullable annotation on any parameter that can be null (I'm not ... More on reddit.com
🌐 r/java
229
100
August 13, 2024
Are there any compile-time checks for @NotNull / @NonNull?

You could try NullAway. It's a plugin for Error Prone, which does compile-time warn/fail checks for various things. I think Error Prone itself also has experimental checks for @Nullable and friends but they're disabled by default, last I looked.

IIRC NullAway assumes that fields, method return values, and method parameters are non-null by default, and you have to annotate them with @Nullable to say otherwise, but local variables can be null.

More on reddit.com
🌐 r/java
56
50
May 14, 2018
🌐
sebhastian
sebhastian.com › java-is-not-null
Java - How to check if a variable or object is not null | sebhastian
March 18, 2022 - When the value of response is not null, then Java will run the println() method inside the if block above. You can also use the Objects.nonNull() method to check whether a variable is not null.
🌐
Medium
tamerardal.medium.com › simplify-null-checks-in-java-writing-clean-code-with-apache-commons-lang-3-e7d3aea207bd
Simplify Null Checks in Java: Writing Clean Code with Apache Commons Lang 3 | by Tamer Ardal | Medium
September 18, 2024 - Two of them are the isEmpty and isNotEmpty methods. These methods check whether the object is null or empty. if (ObjectUtils.isEmpty(myObject)) { // Null or empty } if (ObjectUtils.isNotEmpty(myObject)) { // Not null or empty } Alternatively, ...
🌐
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.
🌐
Silicon Cloud
silicloud.com › home › what are the different ways to check for null in java?
What are the different ways to check for null in Java? - Blog - Silicon Cloud
March 22, 2024 - Use conditional statements for evaluation: if (object == null) { // 对象为null时的处理逻辑 } Make a judgement using the ternary operator. result = (object == null) ? "null" : "not null"; Evaluate with the isNull method from the Objects class (Java 7 and above versions). if […]
Find elsewhere
🌐
Educative
educative.io › answers › what-is-validatenotnull-in-java
What is Validate.notNull in Java?
This method throws a NullPointerException if the object is null. Otherwise, it doesn’t return anything. ... System.out.printf("Validate.notNull(%s) = %s", stringToValidate, Validate.notNull(stringToValidate)); ... System.out.printf("Validate.notNull(%s) = %s", stringToValidate, Validate.notNull(stringToValidate, exceptionMessageFormat)); ... Validate.notNull(hello) = hello Exception in thread "main" java.lang.NullPointerException: Argument should not be null at java.base/java.util.Objects.requireNonNull(Objects.java:347) at org.apache.commons.lang3.Validate.notNull(Validate.java:224) at Main.main(Main.java:12)
🌐
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 Ege Değer | Better Programming
January 26, 2022 - If you are not familiar with Lombok, I highly suggest you to check it out. I personally love Lombok and it makes a developer’s life much easier :) 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.
🌐
GeeksforGeeks
geeksforgeeks.org › java › program-to-check-if-the-string-is-null-in-java
Program to check if the String is Null in Java - GeeksforGeeks
July 12, 2025 - The below example demonstrates how to check if a given string is null using the == relational operator. ... // Java Program to check if // a String is Null class StringNull { // Method to check if the String is Null public static boolean ...
Top answer
1 of 16
2877

This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.

To put this another way, there are two instances where null checking comes up:

  1. Where null is a valid response in terms of the contract; and

  2. Where it isn't a valid response.

(2) is easy. As of Java 1.7 you can use Objects.requireNonNull(foo). (If you are stuck with a previous version then assertions may be a good alternative.)

"Proper" usage of this method would be like below. The method returns the object passed into it and throws a NullPointerException if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.

public Foo(Bar bar) {
    this.bar = Objects.requireNonNull(bar);
}

It can also be used like an assertion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.

Objects.requireNonNull(someobject, "if someobject is null then something is wrong");
someobject.doCalc();

Generally throwing a specific exception like NullPointerException when a value is null but shouldn't be is favorable to throwing a more general exception like AssertionError. This is the approach the Java library takes; favoring NullPointerException over IllegalArgumentException when an argument is not allowed to be null.

(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.

If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.

With non-collections it might be harder. Consider this as an example: if you have these interfaces:

public interface Action {
  void doSomething();
}

public interface Parser {
  Action findAction(String userInput);
}

where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.

An alternative solution is to never return null and instead use the Null Object pattern:

public class MyParser implements Parser {
  private static Action DO_NOTHING = new Action() {
    public void doSomething() { /* do nothing */ }
  };

  public Action findAction(String userInput) {
    // ...
    if ( /* we can't find any actions */ ) {
      return DO_NOTHING;
    }
  }
}

Compare:

Parser parser = ParserFactory.getParser();
if (parser == null) {
  // now what?
  // this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
  // do nothing
} else {
  action.doSomething();
}

to

ParserFactory.getParser().findAction(someInput).doSomething();

which is a much better design because it leads to more concise code.

That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.

try {
    ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
    userConsole.err(anfe.getMessage());
}

Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.

public Action findAction(final String userInput) {
    /* Code to return requested Action if found */
    return new Action() {
        public void doSomething() {
            userConsole.err("Action not found: " + userInput);
        }
    }
}
2 of 16
722

If you use (or planning to use) a Java IDE like JetBrains IntelliJ IDEA, Eclipse or Netbeans or a tool like findbugs then you can use annotations to solve this problem.

Basically, you've got @Nullable and @NotNull.

You can use in method and parameters, like this:

@NotNull public static String helloWorld() {
    return "Hello World";
}

or

@Nullable public static String helloWorld() {
    return "Hello World";
}

The second example won't compile (in IntelliJ IDEA).

When you use the first helloWorld() function in another piece of code:

public static void main(String[] args)
{
    String result = helloWorld();
    if(result != null) {
        System.out.println(result);
    }
}

Now the IntelliJ IDEA compiler will tell you that the check is useless, since the helloWorld() function won't return null, ever.

Using parameter

void someMethod(@NotNull someParameter) { }

if you write something like:

someMethod(null);

This won't compile.

Last example using @Nullable

@Nullable iWantToDestroyEverything() { return null; }

Doing this

iWantToDestroyEverything().something();

And you can be sure that this won't happen. :)

It's a nice way to let the compiler check something more than it usually does and to enforce your contracts to be stronger. Unfortunately, it's not supported by all the compilers.

In IntelliJ IDEA 10.5 and on, they added support for any other @Nullable @NotNull implementations.

See blog post More flexible and configurable @Nullable/@NotNull annotations.

🌐
Quora
quora.com › What-is-the-best-way-to-check-if-a-variable-is-null-before-trying-to-access-its-value-in-Java
What is the best way to check if a variable is null before trying to access its value in Java? - Quora
Answer (1 of 5): I̲n̲ ̲J̲a̲v̲a̲ ̲,̲ ̲t̲h̲e̲ ̲s̲t̲a̲n̲d̲a̲r̲d ̲w̲a̲y ̲i̲s̲ ̲t̲o̲ ̲j̲u̲st̲ ̲d̲o̲ ̲a̲ ̲s̲t̲r̲a̲i̲g̲h̲t̲f̲o̲r̲w̲a̲r̲d̲ ̲n̲u̲l̲l̲ ̲c̲h̲e̲c̲k̲ ̲w̲i̲t̲h̲ ̲`̲i̲f̲ ̲(̲v̲a̲r̲i̲a̲b̲l̲e̲ ̲=̲=̲ ...
🌐
DEV Community
dev.to › scottshipp › better-null-checking-in-java-ngk
Better Null-Checking in Java - DEV Community
January 11, 2019 - There are also the many @notnull annotations available from various libraries such as Spring. ... Nice lib. I do miss ?. and ?? from C# in Java. But I also miss Micronaut/Spring in C# so it's a no brainer :D. Although good thing about JVM frameworks I can combine Groovy and Kotlin with Java to make some stuff have those operators :D. ... I want to recommend you to look at Option<> monad in VAVR it's behavior is similar to the example of NullSafe.
🌐
Wikihow
wikihow.com › computers and electronics › software › programming › java › how to check null in java (with pictures) - wikihow
How to Check Null in Java (with Pictures) - wikiHow
May 15, 2025 - Use “==” to check a variable’s value. A “==” is used to check that the two values on either side are equal. If you set a variable to null with “=” then checking that the variable is equal to null would return true.
🌐
Coderanch
coderanch.com › t › 496486 › java › null-null-java
null and not null in java (Beginning Java forum at Coderanch)
May 22, 2010 - Since you didn't write "== null" or "!= null" in the else block, no, there is no checking whether anything is null. When I said "beware" I didn't mean that NULL values in a database were bad; there are instances where they must be NULL, for example when my middle name is entered in a database.
🌐
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. The question is: is that practical? In the case of programming errors, it is very easy to find out that nulls were passed on. If there are no null-checks and no alternative paths for execution, it will sooner or later lead to a NullPointerException.
🌐
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 returning nulls.
🌐
Reddit
reddit.com › r/java › null safety
r/java on Reddit: Null safety
August 13, 2024 - Conversely, the implication is that if something is not Optional that it is guaranteed to be there and can be accessed safely without a null check. I find this HUGELY beneficial. I also carry this through to interface design. It lets the user of the interface know what’s guaranteed to be there and forces them to proactively deal with things that may not be. ... Using it in fields and parameters is absolutely fine. I've never heard any rational reason to think otherwise. ... It’s sadly not surprising that the top answer to a question in a Java sub about null checking features Optionals and not, you know…