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
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
🌐
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.
🌐
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).
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
April 8, 2019 - 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.
🌐
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 - But also the code in the function we are calling should never return null. 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.
Find elsewhere
🌐
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.
🌐
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.
🌐
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.
🌐
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.
🌐
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.
🌐
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̲ ̲=̲=̲ ...
🌐
nipafx
nipafx.dev › inside-java-newscast-7
Handling null and Upgrading Past Java 8 - Inside Java Newscast #7 // nipafx
Object obj = null; // old-style ... executed · In switch, if JEP 406 gets released in Java 17 as it is proposed now, the case keyword is used and usually, something like case String s won't match null either (it only will if ...
Published   July 1, 2021
🌐
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 - implementation 'org.apache.commons:commons-lang3:3.17.0' // Check the version · ObjectUtils has several useful methods that you can use to check objects and assign default values. Two of them are the isEmpty and isNotEmpty methods.
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.

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