Using an alternative value in Java if a variable is null

java logo

You can often run into a situation where you would like to use a variable’s value but you are not sure what that variable contains.

This is a very common situation for example when you use a value that was passed to your method as a parameter. The caller can provide any value, even null. This is not a problem in all cases, but if you for example, try to call a method on the object referenced by the variable, you could get a  NullPointerException if the variable’s value is null.

Other reason could be that you are passing the value to another method and don’t know if that method will react well to getting a null value, or just throw an exception. In this case it is also advisable to make sure that you don’t pass a null value. (Of course, there are cases when you would like the called method to fail if a null value is passed. In this case you don’t want to replace the null value with something else.)

There are different ways to do this, I show you some of them in the next sections of this tutorial.

The verbose way

You can just simply check for null value and set an alternative if the variable contains null.

if(user == null) {
    user = new User(1L);
}

The shorter way

This is a shorthand version of the first one. It is shorter, but less readable.

user = (user == null) ? new User(1L) : user;

The Google Guava way

This is the way I like to do it. This solution is concise and very readable in my opinion. You only need the widely used Google Guava library for it, which maybe you are using already anyway.

import com.google.common.base.MoreObjects;

// ...

user = MoreObjects.firstNonNull(user, new User(1L));