How to check if an object reference is not null?

Usually, if not always, we use the `if` statement combined with `==` or `!=` operators to check if an object reference is null or not. We do this to validate arguments passed to constructors or methods doesn’t contain a null value. These null check can be seen as clutter in our code.

The solution is to use the `java.util.Objects` class. This static utility class provides methods like `requireNonNull(T)` and `requireNonNull(T, String)` to check if the specified object reference is not null. If null, these methods will throw a `NullPointerException`. Using the second method variant we can customise the exception message.

The example below shows how we use these methods.

“`java
package org.kodejava.util;

import java.util.Objects;

public class ObjectsNullCheckDemo {
private String firstName;
private String lastName;

/**
* Validate constructor arguments. The firstName and lastName
* arguments can't be null. A NullPointerException with the
* specified message will be thrown.
*/
public ObjectsNullCheckDemo(String firstName, String lastName) {
this.firstName = Objects.requireNonNull(firstName,
"First name can't be null.");
this.lastName = Objects.requireNonNull(lastName,
"Last name can't be null.");
}

public static void main(String[] args) {
// This line is fine.
ObjectsNullCheckDemo demo = new ObjectsNullCheckDemo("John", "Doe");
System.out.println("demo = " + demo);

try {
// This line produce a NullPointerException
ObjectsNullCheckDemo demo1 = new ObjectsNullCheckDemo("Alice", null);
} catch (Exception e) {
e.printStackTrace();
}

String name = null;
try {
// The line below will throw java.lang.NullPointerException.
Objects.requireNonNull(name);
} catch (Exception e) {
e.printStackTrace();
}
}

public void setFirstName(String firstName) {
// First name can't be null.
this.firstName = Objects.requireNonNull(firstName,
"First name can't be null.");
}

public void setLastName(String lastName) {
// Last name can't be null.
this.lastName = Objects.requireNonNull(lastName,
"Last name can't be null.");
}

@Override
public String toString() {
return "ObjectsNullCheckDemo{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
“`

Running the code above will print the following result:

“`text
demo = ObjectsNullCheckDemo{firstName='John', lastName='Doe'}
java.lang.NullPointerException: Last name can't be null.
at java.base/java.util.Objects.requireNonNull(Objects.java:233)
at org.kodejava.util.ObjectsNullCheckDemo.<init>(ObjectsNullCheckDemo.java:17)
at org.kodejava.util.ObjectsNullCheckDemo.main(ObjectsNullCheckDemo.java:28)
java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:208)
at org.kodejava.util.ObjectsNullCheckDemo.main(ObjectsNullCheckDemo.java:36)
“`

Leave a Reply