Since Java 9 the methods requireNonNullElse
and requireNonNullElseGet
are part of the java.util.Objects
class.
The method requireNonNullElse
accepts two arguments.
The first argument is an object that will be returned if that object is not null
.
The second argument is an object to be returned when the first argument is null
.
With this method you can replace the following ternary operator if (a != null) ? a : b
(or if (a == null) ? b : a)
with Objects.requireNonNullElse(a, b)
.
The method requireNonNullElseGet
allows to define a Supplier
function as second argument.
The Supplier
is only invoked when the first argument is null
, so it is lazy and will only be invoked when the first argument is null
.
In the following example the methods are invoked with different arguments that are null
and not null
.
package mrhaki; import static java.util.Objects.requireNonNullElse; import static java.util.Objects.requireNonNullElseGet; public class NullDefault { public static void main(String[] args) { // The first argument of requireNonNullElse is returned // if the value is not null. assert requireNonNullElse("Hello", "Hi").equals("Hello"); // The second argument of requireNonNullElse is returned // if the first argument is null. assert requireNonNullElse(null, "Hi").equals("Hi"); // You can also use a Supplier function to calculate the value // to be returned if the first argument is null. // This function is only invoked when the first argument is null. // Very useful if calculating the value is resource intensive. assert requireNonNullElseGet("Hello", () -> "Hi").equals("Hello"); assert requireNonNullElseGet(null, () -> "Hi").equals("Hi"); } }
Written with Java 21.