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
🌐
Upwork
upwork.com › resources › articles › {name}
Null in Java: Understanding the Basics - Upwork
August 5, 2024 - It is neither an object nor a type (a common misconception some newcomers to the Java language grapple with). The concept of null was introduced in programming languages to represent the absence of a value or a non-existent object.
Discussions

java - How to avoid != null statements? - Software Engineering Stack Exchange
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. ... In Java 8, a new ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
April 9, 2018
FResult: A unified approach to null safety and error handling in Java
Nice as an exercise for the person who wrote that. Other than that it goes against the idiom and is unlikely to gain traction. Of course, this approach works very well for languages that support pattern matching. More on reddit.com
🌐 r/java
44
66
May 23, 2021
Why ConcurrentHashMap does not support null values

The title would more correctly be "Why does ConcurrentHashMap not support null keys or values". Neither supports nulls.

The reason ConcurrentHashMap does not support null keys is that Doug Lea didn't want to include key masking, the use of a special value for signifying NULL such as NULL_OBJECT in zathar's example in ConcurrentHashMap. Null values are disallowed because with null values in the map the result of get() is ambiguous as to whether the key was not found or the mapping for that key is null, ie. you are required to use containsKey() to determine if there is a mapping for a key, get() is ambiguous because the mapping could be key -> null

For HashMap/Hashtable :

 Object value;
 if(map.containsKey(key))
    value = map.get(key);
else
    throw new NoSuchElementException("No mapping for " + key);

For ConcurrentHashMap/TreeMap:

 Object value = map.get(key);
 if(null == value) 
     throw new NoSuchElementException("No mapping for " + key);

Generally, allowing null membership in Collections is regarded as a mistake. All future Java APIs especially collections will be null hostile. Null, if used in the API at all, will be used for signifying conditions (such as no mapping for a key being present) rather than as a value of the collection.

More on reddit.com
🌐 r/java
9
32
February 23, 2011
Java lang null pointer exception when using a spinner...
I am assuming this is line 24? spinner.setAdapter(adapter); And spinner is null? According to the docs, findViewById returns "The view if found or null otherwise." Verify that R.id.spinner actually points at something that exists. More on reddit.com
🌐 r/androiddev
10
2
October 2, 2014
🌐
GeeksforGeeks
geeksforgeeks.org › java › interesting-facts-about-null-in-java
Interesting facts about null in Java - GeeksforGeeks
September 3, 2024 - An empty string is a string that contains no characters, while an empty array is an array that contains no elements. The Java programming language has a built-in null type, called "null", which is a subtype of all reference types.
🌐
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
In Java, null is a special value that indicates that a reference variable does not point to any object. Think of a variable as a box, and an object as something you put inside the box. If the box is empty, the variable is null.
🌐
Quora
quora.com › Why-is-null-null-true-in-java
Why is null == null true in java? - Quora
Answer (1 of 8): In java only references can have the value null. As per the Java Language Specification it's "merely a special literal that can be of any reference type". For references == returns true if and only if the value of the two references ...
Find elsewhere
🌐
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 isStringNull(String s) { // Compare the string with null // using == relational operator // and return the result if (s == null) return true; else return false; } // Driver code public static void main(String[] args) { // Test strings String s1 = "GeeksforGeeks"; String s2 = null; System.out.println("Is string [" + s1 + "] null?
🌐
Baeldung
baeldung.com › home › java › core java › check if all the variables of an object are null
Check If All the Variables of an Object Are Null | Baeldung
January 8, 2024 - The null value in Java means the absence of a variable’s value. Technically, a variable containing null doesn’t point to any position in memory or wasn’t initialized yet. That can only occur with instance variables. Primitive variables such as int, double, and boolean can’t hold null. Checking for null variables in our programs is helpful to avoid unexpected errors like IllegalArgumentException or a NullPointerException.
🌐
Better Programming
betterprogramming.pub › checking-for-nulls-in-java-minimize-using-if-else-edae27016474
Checking for Nulls in Java? Minimize Using “If Else”
January 26, 2022 - One of the most common place Optional is used in the project that I am currently working on is while retrieving data from the database. ... The returned value from this method will never be null. If it is null, the returned value will be Optional.empty().
🌐
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̲ ̲=̲=̲ ...
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
January 8, 2024 - According to the Javadoc for NullPointerException, it’s thrown when an application attempts to use null in a case where an object is required, such as:
🌐
W3Schools
w3schools.com › sql › sql_null_values.asp
SQL NULL Values - IS NULL and IS NOT NULL
SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NOT NULL; Try it Yourself » ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected] · If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected] · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
CodeGym
codegym.cc › java blog › strings in java › java: check if string is null, empty or blank
Java: Check if String is Null, Empty or Blank
October 11, 2023 - Very often in programming, a String is assigned null to represent that it is completely free and will be used for a specific purpose in the program. If you perform any operation or call a method on a null String, it throws the java.lang.NullPointerException. Here is a basic example illustrating declaration of a null String.
🌐
Coderanch
coderanch.com › t › 556362 › java › null-check-essential-object
Is null check really essential for each and every object [Solved] (Java in General forum at Coderanch)
October 20, 2011 - Is there any way you can prevent nulls remaining in your code?That is prone to NullPointerExceptions (NPE), but allowing nulls into a program is probably the mistake, rather than the NPE itself. In testing, you will know about that early, if you change the constructor to this:That way you can be confident those nulls won’t get into your object in the first place. ... I believe that the Java original designers were fast and loose with null values.
🌐
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 - A null indicates that a variable doesn't point to any object and holds no value. You can use a basic 'if' statement to check a null in a piece of code. Null is commonly used to denote or verify the non-existence of something. Within that...
🌐
DEV Community
dev.to › scottshipp › better-null-checking-in-java-ngk
Better Null-Checking in Java - DEV Community
January 11, 2019 - Any declared but uninitialized variable automatically references null, and other Java language constructs like try/catch force variables to have to be declared in an outer scope where null is one of the only valid choices.
🌐
DataCamp
datacamp.com › doc › java › null
null Keyword in Java: Usage & Examples
The null keyword in Java is a literal that represents a null reference, one that points to no object.
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.

🌐
Logit
logit.io › blog › post › null-in-java
The Concept Of Null In Java
February 4, 2025 - Null is a reserved word (keyword) in Java for literal values. It is a literal similar to the true and false. In Java, null is a keyword much like the other keywords public, static or final.
🌐
Baeldung
baeldung.com › home › java › java numbers › check if an integer value is null or zero in java
Check if an Integer Value Is Null or Zero in Java | Baeldung
January 8, 2024 - Java Null · Optional · Course – Black Friday 2025 – NPI EA (cat= Baeldung) Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until next Monday: >> EXPLORE ACCESS NOW · Partner – Orkes – NPI EA (cat=Spring) Modern software architecture is often broken.