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
🌐
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 - If you set a variable to null with “=” then checking that the variable is equal to null would return true. ... You can also use “!=” to check that a value is NOT equal.
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
April 8, 2019 - Now let’s suppose that we’re working with an API that cannot accept null parameters or can return a null response that has to be handled by the client. This presents the need for us to check the parameters or the response for a null value. Here, we can use Java Assertions instead of the traditional null check conditional statement:
🌐
Javatpoint
javatpoint.com › how-to-check-null-in-java
How to Check null in Java
Java String valueOf() Java Integer getInteger() Method · Package class · Java abstract Keyword · Java boolean Keyword · Java byte keyword · Java case keyword · Java char keyword · Java class keyword · Java double keyword · Java float keyword · Java int keyword · Java new Keyword · Java null reserved word ·
🌐
DataCamp
datacamp.com › doc › java › null
null Keyword in Java: Usage & Examples
In this example, the String variable str is initialized to null. The if statement checks if str is null and prints a message accordingly.
🌐
DEV Community
dev.to › scottshipp › better-null-checking-in-java-ngk
Better Null-Checking in Java - DEV Community
January 11, 2019 - Other languages like Groovy and C# have a nice null-conditional operator that allows the programmer to specify that a chain of references might contain a null somewhere along the way, and a natural way to deal with that is to just short-circuit the chain of calls and result in a null value. Here’s the first example from the C# documentation: Java doesn’t allow operator creation, so we can’t imitate this behavior exactly, but I have used some of the functional features found in Java 8, such as method references, to create similar functionality. Take a look. As a motivating example, finding a user’s zip code in their account might look similar to this in standard Java: That’s three null checks in the space of ten lines.
🌐
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 - To check if a string is null in Java, we can use the "==" operator that directly compares the string reference with null.
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.

Find elsewhere
🌐
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 ...
January 26, 2022 - If a value is present, returns the value, otherwise throws NoSuchElementException.¹ · In the case of null, if you want to throw an exception you could just use orElseThrow().
🌐
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̲ ̲=̲=̲ ...
🌐
Delft Stack
delftstack.com › home › howto › java › java check if object is null
How to Check if an Object Is Null in Java | Delft Stack
February 12, 2024 - It encourages a functional programming style by allowing chained operations on values that may or may not be present. For null checks, the Optional.ofNullable() method can be used to wrap an object, and subsequent operations can be performed ...
🌐
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).
🌐
Stack Abuse
stackabuse.com › java-check-if-string-is-null-empty-or-blank
Java: Check if String is Null, Empty or Blank
February 28, 2023 - String string = "Hello there"; if (string == null || string.equals("") || string.trim().equals("")) System.out.println("String is null, empty or blank"); else System.out.println("String is neither null, empty nor blank"); In much the same fashion as the before, if the trimmed string is "", it was either empty from the get-go, or was a blank string with 0..n whitespaces: ... The Apache Commons is a popular Java library that provides further functionality. StringUtils is one of the classes that Apache Commons offers. This class contains methods used to work with Strings, similar to the java.lang.String.
🌐
Programiz
programiz.com › java-programming › examples › string-empty-null
Java Program to Check if a String is Empty or Null
class Main { public static void main(String[] args) { // create null, empty, and regular strings String str1 = null; String str2 = ""; String str3 = " "; // check if str1 is null or empty System.out.println("str1 is " + isNullEmpty(str1)); // check if str2 is null or empty System.out.println("str2 ...
🌐
Java2Blog
java2blog.com › home › core java › java basics › check if object is null in java
Check if Object Is Null in Java - Java2Blog
November 29, 2023 - The most basic and efficient way to check if an object is null is by using the == operator. ... Object myObject = null;: This line declares a variable named myObject of the type Object, which is a class in Java.
🌐
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 - In this tutorial, we’ll learn four approaches to check if all variables of an object are null. 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.
🌐
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 - Simplify Null Checks in Java: Writing Clean Code with Apache Commons Lang 3 In Java, null checks are generally done using == or !=. In addition, if we want to do an empty check, our condition will …
🌐
DZone
dzone.com › coding › java › checking for null values in java with objects.requiresnonnull()
Checking for Null Values in Java with Objects.requiresNonNull()
October 3, 2014 - import java.util.Objects; public void foo(SomeClass obj) { Objects.requireNonNull(obj, "obj must not be null"); // work with obj } ... Published at DZone with permission of Michael Scharhag, DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. Modernizing Apache Spark Applications With GenAI: Migrating From Java to Scala
🌐
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 - D is correct by chance : you switch the String.valueOf() call to obj.toString and I had to look the doc "if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned." If it was a pure replacement I would raise an eyebrow during code review, but that code is 100% correct. [EDIT] Why are you even converting unknown type of elements into String? In real-life situations, I would recheck the requirements. ... News, Technical discussions, research papers and assorted things of interest related to the Java programming language NO programming help, NO learning Java related questions, NO installing or downloading Java questions, NO JVM languages - Exclusively Java