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
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
1 week ago - 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

How and When do you guys check "null"?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
20
4
September 4, 2024
What are the different ways to check if an object is null in Java besides `== null`? - TestMu AI Community
I need to create a method that checks whether a class instance is null or not. Normally, I would just use == null, but I’m curious if there are any other ways to perform this check in Java. Here’s my situation: I have 70-80 class instances, all of which extend the same base class BaseEntity. More on community.testmu.ai
🌐 community.testmu.ai
0
February 10, 2025
Best way to handle nulls in Java? - Software Engineering Stack Exchange
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/ ... Java 8 adds these annotation to help code checking tools like IDEs catch problems. More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
February 23, 2011
Difference between 0 and null
It's funny, but how does it change the volume? More on reddit.com
🌐 r/ProgrammerHumor
190
13922
February 18, 2017
🌐
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. It further shows how to check if it is a valid null String.
🌐
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/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).
🌐
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 - In case of lists, maps etc, isEmpty() checks if the collection/map is null or have size of 0.
Find elsewhere
🌐
TestMu AI Community
community.testmu.ai › ask a question
What are the different ways to check if an object is null in Java besides `== null`? - TestMu AI Community
February 10, 2025 - I need to create a method that checks whether a class instance is null or not. Normally, I would just use == null, but I’m curious if there are any other ways to perform this check in Java. Here’s my situation: I have…
🌐
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.
🌐
Quora
quora.com › In-Java-how-do-you-check-a-long-for-null
In Java, how do you check a long for null? - Quora
Answer (1 of 12): a “long” is a scalar type, so it cannot be null. You’ll get a NullPointerException. If you mean “Long” the object, then the test is just like anything else “myLongObject == null”
🌐
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 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.

🌐
DEV Community
dev.to › scottshipp › better-null-checking-in-java-ngk
Better Null-Checking in Java - DEV Community
January 11, 2019 - 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.
🌐
Coderanch
coderanch.com › t › 607794 › java › check-long-null
how to check whether long value is null or not (Beginning Java forum at Coderanch)
March 21, 2013 - You can not declare a local variable (that is, defined inside a function ) private. Whereas a Long object reference can be null, a primitive long can not. ... Sorry my bad. It was : "".equals(..); ... > When I am trying to check the value as null its giving compile time error.
🌐
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)
August 23, 2023 - All the other moderators will disagree with me for this (‍), but you should always throw a NullPointerException whenever you encounter an inappropriate null. If you elect to use throw new WhateverException should you still use the throws keyword in the method signature? Yes, I do feel I need to be pedantic. Since you are new to Java®, I think you should learn the precise jargon.
🌐
LinkedIn
linkedin.com › pulse › java-null-checks-statements-eric-riml
Java, Null checks and IF statements
May 14, 2021 - So, why are IF statements in Java nearly always written like this? if (myVariable.getMyProperty() != null && myVariable.getMyProperty().equals(SomeEnumClass.SOME_CONSTANT)) { ... } ... Look familiar? Why do I have to check for null, again?
🌐
DZone
dzone.com › coding › languages › why i never null-check parameters
Why I Never Null-Check Parameters
December 4, 2018 - Methods and constructors should not check for nulls ... Constructors with multiple parameters that aren't required should consider using the Builder Pattern. Methods that returned null should return Optional or a special implementation of whatever logic was expected on null previously. Java (programming language) Coding best practices programming langauge
🌐
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 - As we can see, we’ve tested our usingStandardWay() method by passing three Integer objects to it: zero, null, and 42. We’ll use these three Integer objects as inputs for further tests in this tutorial.
🌐
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.
🌐
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.