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
🌐
DEV Community
dev.to › scottshipp › better-null-checking-in-java-ngk
Better Null-Checking in Java - DEV Community
January 11, 2019 - Here’s a common example, from one of the official Java tutorials, which is considered good Java: If there were other code that used the out variable later, it would have to perform null-checking (as seen in line 19) again.
Top answer
1 of 3
22

Update: Pattern matching for switch arrived in Java 21.

tl;dr

switch expressions != pattern matching with switch

You are mixing up the relatively new feature of switch expressions with the still-not-released feature of pattern matching with switch.

The switch feature in Java has been evolving through 3 phases, two completed:

  • switch statement (original feature in Java 1)
  • switch expression (Java 14+)
  • Pattern matching for switch, including case null (previewed in Java 17, 18, 19, & 20)

Do not conflate switch expressions with pattern matching

Classic switch

Understand that historically, the Java switch statement has been hostile to null checks. See this Question, How to use null in switch. As shown there, code such as this:

switch ( i ) {
    case null:
        doSomething0();
        break;    
}

… was not possible.

switch expressions

Fast forward to Java 14, when switch expressions was added to Java. A switch can return a value. See JEP 361: Switch Expressions.

The switch expressions feature provides the syntax seen in your first code example:

return switch ( testEnum ) {
  case FOO -> newFoo();
  case BAR -> newBar();
}

But read the JEP. No mention of null — « crickets ».

Pattern matching for switch

Fast forward further, to JEP 406: Pattern Matching for switch (Preview). Note that this is a preview feature in Java 17, not a final, officially released feature. (To understand how preview features work, read JEP 12: Preview Features.)

In that JEP 406, notice its second goal: Allow the historical null-hostility of switch to be relaxed when desired.

Now search that page for “null” — 73 hits! That page explains the former policy of the Java language:

Traditionally, switch statements and expressions throw NullPointerException if the selector expression evaluates to null

Notice the mention of statements, the original switch syntax, and additionally expressions, the new syntax used in your code. In both cases, null check was forbidden.

That page goes on to explain the changes that motivate the inclusion of support for null checks. Read the JEP for well-written details.

The upshot is that you can use case null in a switch in Java 17 — but only if you go out of your way to enable the preview feature.

Arrived in Java 21

This feature arrived in Java 21. See JEP 441: Pattern Matching for switch.

Example

Let's try this code example. Notice how we use plain old syntax here, without the ->. The arrow operator is not related to our discussion here.

String x = null;
switch ( x )
{
    case "starburst":
        System.out.println( "Is starburst." );
        break;
    case null:
        System.out.println( "Whoops, null." );
        break;
    default:
        System.out.println( "Some other value found." );
        break;
}
2 of 3
1

This command line works for me:

$ javac -version
javac 17.0.3
$ javac  -source 17 -Xlint:preview --enable-preview org/kablambda/Main.java
org/kablambda/Main.java:10: warning: [preview] null in switch cases is a preview feature and may be removed in a future release.
            case null -> "c";
                 ^
1 warning
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
January 8, 2024 - 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.
🌐
Reddit
reddit.com › r/javahelp › how and when do you guys check "null"?
r/javahelp on Reddit: How and When do you guys check "null"?
September 4, 2024 -

I'm 4 y experienced Java dev but still it's unclear how and when to check nullity sometimes and it happened today. Let's say there is a table called students and it has column called `last_name` which is not null.

create table students (
    last_name varchar(255) not null
)

You have written validation code to ensure all required column is appeared while inserting new record and there is a method that needs last_name of students. The parameter of this method may or may not come from DB directly(It could be mapped as DTO). In this case do you check nullity of `last_name` even though you wrote validation code? Or just skip the null check since it has not null constraint?

I know this depends on where and how this method is used and i skipped the null check because i think this method is not going to be used as general purpose method only in one class scope.

Top answer
1 of 6
17
I think there are a few approaches: Check everywhere. Be super defensive, and check the inputs to essentially every function for nulls and other violated invariants Define a boundary. Try to create clear "boundaries" in your code, for example by validating all external inputs in one layer, and then allowing the layers below this to assume that their inputs are valid Use types to your advantage, e.g. by having a PhoneNumber class rather than just using a String (which indicates that the phone number has been validated), or a PendingOrder and DeliveredOrder class rather than a single Order class with an isDelivered property (which prevents you from using orders in unintended ways) YOLO. Don't have a consistent approach to validating things
2 of 6
4
Ideally you write your interfaces and methods such that they don't return nulls and your objects don't have any properties set to null (so use Optional as return type where it makes sense, and/or return 'empty' objects, primitives, or throw exceptions). Personally, if I write a public method that could return 'null', I make it explicitly clear in the name itself, for example: `getStatusDetailsOrNull()` - but typically, I would return an Optional. Outside of that, you check the contract of the method. If the method does not guarantee a non-null response, then you check it. If you don't know, then you also check for non-null. Also use a good static checker, which will flag some areas where null can occur. In your example, you can enforce the DTO to never have a null value. Make it an immutable object, and guarantee that either instance creation fails, or no DTO field is ever null. You can then add a bunch of unit tests to make sure that a future developer does not break this accidentally. I'm not a huge fan of just checking for null everywhere because it does liter your code with superfluous checks, and it communicates to others that some method could be returning null (even though the contract may state that it doesn't).
🌐
Oracle
oracle.com › java › technical details
Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!
We've come a long way from writing painful nested null checks to writing declarative code that is composable, readable, and better protected from null pointer exceptions. In this article, we have seen how you can adopt the new Java SE 8 java.util.Optional<T>. The purpose of Optional is not to replace every single null reference in your codebase but rather to help design better APIs in which—just by reading the signature of a method—users can tell whether to expect an optional value.
Find elsewhere
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.

🌐
Javatpoint
javatpoint.com › how-to-check-null-in-java
How to Check null in Java
How to Check null in Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
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)
There are many methods in the standard Java API whose documentation says "Don't pass null to me or you're gonna get a NPE". That would generally be my preference for this kind of method. ... Welcome to the Ranch Who has told you to write that utility class? I would say you should use that sort of code only as an exercise, since you will find existing code to do the same things here. It looks a bit like reinventing the wheel to me. The only legacy date and time code anybody should use is java.sql.Date, because that is what you get out of a result set.
🌐
Reddit
reddit.com › r/java › cleanest way to check for null on a string?
Cleanest way to check for null on a String? : r/java
May 8, 2024 - But as an FYI instead of "String.valueOf" you can use "java.util.Objects.toString(Object o, String nullDefault)" instead, which was added in Java 1.7. If you replaced String.valueOf(someObject.get("someKey")) with Objects.toString(someObject.get("someKey"), null) then it works just fine when ...
🌐
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.
🌐
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 - You can also use “!=” to check that a value is NOT equal. ... Use an “if” statement to create a condition for the null. The result of the expression will be a boolean (true or false) value.
🌐
LabEx
labex.io › tutorials › java-how-to-check-if-an-object-is-null-in-java-560011
How to Check If an Object Is Null in Java | LabEx
Learn how to check if an object is null in Java using the equality operator, combining null and type checks, and the Optional class to prevent NullPointerException errors and write more robust code.
🌐
TutorialsPoint
tutorialspoint.com › checking-for-null-or-empty-in-java
Checking for Null or Empty in Java.
The following is an example of checking if a string is null or empty using the isBlank() method:
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.

🌐
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̲ ̲=̲=̲ ...
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.