It's an old solution to a problem that happened way before Java. I'm old, but I still use it because it's memory efficient and fast. Situational example.. You have a function that returns an int. If you know its always supposed to be positive, it's pretty common to return -1 to communicate that something went wrong, is absent, isn't finished doing something, etc. It's quick. Only requires a single 32/64 bit piece of memory. Solid choice to use when documented well. Instead of integer, let's say you have a class that hypothetically takes up 200 bytes of memory. I don't want to just stop my program because something isn't in a list, and I can't just return -1. I could create a default class that represents a problem just like "-1" does, but that's going to allocate 200 bytes. Assigning the variable to 'null' doesn't allocate 200 bytes. It just points to a universal 'null' memory address that is well understood by the JVM to mean "nothing." "Nothing" saves space and saves a lot of computation power from .equals(...) and even garbage collection. Is it worth having to rely on performing a null check constantly? Actually, yes. It is usually worth it. If people are used to dealing with null, it's not a problem. Coming from different languages where null is not allowed, you get a lot of NullPointerExceptions. Skill issue, though. Edit: Removed most mentions of exceptions to focus on why a new programmer might see "return null" and to appease the Spring devs who believe checked exceptions are relative to OPs question. Answer from MrRickSancezJr on reddit.com
🌐
Medium
medium.com › javarevisited › just-dont-return-null-dcdf5d77128f
Just Don’t Return null!
February 16, 2022 - Return a “Special Case” object A special case object is something that we return instead of returning null. There’s a pattern called null value object which I have already explained in the other article so I am not going to explain it here again but instead, I am going to use Java 8 Optional.empty() which is just Java’s implementation of that patter.
🌐
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: ... public void doSomething() { String result = doSomethingElse(); if (result.equalsIgnoreCase("Success")) // success } } private String doSomethingElse() { return null; }
🌐
Coderanch
coderanch.com › t › 417559 › java › return-null
can we return null? (Java in General forum at Coderanch)
Then programmers that call your method know that they should check if the return value is null: SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6 How To Ask Questions How To Answer Questions ... Hi there, Yes it can be considered a valid return technique, it just needs to be clearly documented in the Javadoc for that method e.g.
Top answer
1 of 12
77
It's an old solution to a problem that happened way before Java. I'm old, but I still use it because it's memory efficient and fast. Situational example.. You have a function that returns an int. If you know its always supposed to be positive, it's pretty common to return -1 to communicate that something went wrong, is absent, isn't finished doing something, etc. It's quick. Only requires a single 32/64 bit piece of memory. Solid choice to use when documented well. Instead of integer, let's say you have a class that hypothetically takes up 200 bytes of memory. I don't want to just stop my program because something isn't in a list, and I can't just return -1. I could create a default class that represents a problem just like "-1" does, but that's going to allocate 200 bytes. Assigning the variable to 'null' doesn't allocate 200 bytes. It just points to a universal 'null' memory address that is well understood by the JVM to mean "nothing." "Nothing" saves space and saves a lot of computation power from .equals(...) and even garbage collection. Is it worth having to rely on performing a null check constantly? Actually, yes. It is usually worth it. If people are used to dealing with null, it's not a problem. Coming from different languages where null is not allowed, you get a lot of NullPointerExceptions. Skill issue, though. Edit: Removed most mentions of exceptions to focus on why a new programmer might see "return null" and to appease the Spring devs who believe checked exceptions are relative to OPs question.
2 of 12
6
In some functions, if you can't find the value you want to return, you might return null instead. For example, imagine you have a method that is meant to search for an object in a collection that fits certain criteria. If your collection does not contain such an object, then your method might handle that by returning null. Generally though, this would not be considered great software design. It is very easy to run into runtime errors this way, for example, if a developer using such a method does not realize that it could return null.
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Return Optional not null
import java.time.LocalDate; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; public final class Human { /** Constructor. @param name never null or empty @param address never null, can be empty @param friends never null, can be empty; a defensive copy is made @param birthDate can be null! */ public Human(String name, String address, Set<Human> friends, LocalDate birthDate){ this.name = Objects.requireNonNull(name).trim(); if (this.name.length() == 0){ throw new IllegalArgumentException("Name is empty."); } this.address = Objects.requireNonNull(address).trim(); this.friends.addAll(Objects.requireNonNull(friends)); //defensive copy this.birthDate = birthDate; //immutable, no need to copy } //..elided /** Never null or empty.
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.

Top answer
1 of 16
103

StackOverflow has a good discussion about this exact topic in this Q&A. In the top rated question, kronoz notes:

Returning null is usually the best idea if you intend to indicate that no data is available.

An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.

Additionally, returning a null will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code - attempting to access a member of nothing makes no sense. Accessing members of an empty object will not fail meaning bugs can go undiscovered.

Personally, I like to return empty strings for functions that return strings to minimize the amount of error handling that needs to be put in place. However, you'll need to make sure that the group that your working with will follow the same convention - otherwise the benefits of this decision won't be achieved.

However, as the poster in the SO answer noted, nulls should probably be returned if an object is expected so that there is no doubt about whether data is being returned.

In the end, there's no single best way of doing things. Building a team consensus will ultimately drive your team's best practices.

2 of 16
102

In all the code I write, I avoid returning null from a function. I read that in Clean Code.

The problem with using null is that the person using the interface doesn't know if null is a possible outcome, and whether they have to check for it, because there's no not null reference type.

In F# you can return an option type, which can be some(Person) or none, so it's obvious to the caller that they have to check.

The analogous C# (anti-)pattern is the Try... method:

public bool TryFindPerson(int personId, out Person result);

Now I know people have said they hate the Try... pattern because having an output parameter breaks the ideas of a pure function, but it's really no different than:

class FindResult<T>
{
   public FindResult(bool found, T result)
   {
       this.Found = found;
       this.Result = result;
   }

   public bool Found { get; private set; }
   // Only valid if Found is true
   public T Result { get; private set;
}

public FindResult<Person> FindPerson(int personId);

...and to be honest you can assume that every .NET programmer knows about the Try... pattern because it's used internally by the .NET framework. That means they don't have to read the documentation to understand what it does, which is more important to me than sticking to some purist's view of functions (understanding that result is an out parameter, not a ref parameter).

So I'd go with TryFindPerson because you seem to indicate it's perfectly normal to be unable to find it.

If, on the other hand, there's no logical reason that the caller would ever provide a personId that didn't exist, I would probably do this:

public Person GetPerson(int personId);

...and then I'd throw an exception if it was invalid. The Get... prefix implies that the caller knows it should succeed.

Find elsewhere
🌐
JanBask Training
janbasktraining.com › community › java › how-to-return-null-in-java
How to return null in java? | JanBask Training Community
October 6, 2022 - In ReverseString(), I would say return an empty string because the return type is string, so the caller is expecting that. Also, this way, the caller would not have to check to see if a NULL was returned. In FindPerson(), returning NULL seems like a better fit. Regardless of whether or not NULL or an empty Person Object (new Person()) is returned the caller is going to have to check to see if the Person Object is NULL or empty before doing anything to it (like calling UpdateName()).
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.

🌐
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 - This method returns an instance of User1 and is assigned to the variable getUserObject. Next, we encounter an if-else statement that checks if the object referenced by getUserObject is null using the equality operator (==). If the condition evaluates to true, the program enters the if block, and the message Object is Null is printed to the console.
🌐
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 ObjectUtils’s allNull() method has a generic API that handles any type and number of parameters. That method receives an array of Objects and returns true if all values in that array are null.
🌐
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 - Lets say that you have a stream of data, and you will perform some chain operations on this stream but before that you want to filter out nulls if there are any. final var list = Arrays.asList(1, 2, null, 3, null, 4); list.stream() .filter(Objects::nonNull) .forEach(System.out::print); ... Checks that the specified object reference is not null and throws a customized NullPointerExceptionif it is. This method is designed primarily for doing parameter validation in methods and constructors with multiple parameters.² · Returns the first argument if it is non-null and otherwise returns the non-null second argument.³
🌐
sebhastian
sebhastian.com › java-is-not-null
Java - How to check if a variable or object is not null | sebhastian
March 18, 2022 - class Main { public static void main(String[] myArgs) { String response = getNull(); if(response != null){ System.out.println(response.length()); } else { System.out.println("response is NULL!"); } } private static String getNull() { return null; } } To summarize, you can check whether a variable or object is not null in two ways: ... Checking for null values before executing further operations will help you to avoid the NullPointerException error. And that’s how you check if a variable or object is not null in Java.
🌐
Upwork
upwork.com › resources › articles › {name}
Null in Java: Understanding the Basics - Upwork
August 5, 2024 - It’s important to note that the ... value or the null literal itself. The java.lang.NullPointerException is thrown in Java when you point to an object with a null value....
🌐
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.
🌐
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 - For example, if the value is null, then print text “object is null”. If “==” does not find the variable to be null, then it will skip the condition or can take a different path.