How do I handle null safely using Objects.requireNonNullElse?

The Objects.requireNonNullElse method, introduced in Java 9, provides a safe and convenient way to handle null references by returning a default value if the provided object is null. This method ensures that you won’t get a NullPointerException in cases where you expect an object but want a fallback when it’s null.

Syntax

public static <T> T requireNonNullElse(T obj, T defaultObj)

Parameters

  • obj: The object to check for null.
  • defaultObj: The object to return if obj is null. This cannot be null; otherwise, a NullPointerException will be thrown.

Returns

  • If obj is not null, it returns obj.
  • If obj is null, it returns defaultObj.

Key Features

  • Ensures defaultObj is never null. If you pass a null defaultObj, the code will throw a NullPointerException.
  • Useful when you want a non-null value without writing explicit if-else conditions.

Example Usage

import java.util.Objects;

public class Main {
    public static void main(String[] args) {
        String value = null;
        String defaultValue = "Default Value";

        // Using Objects.requireNonNullElse
        String result = Objects.requireNonNullElse(value, defaultValue);

        // Prints: Default Value
        System.out.println(result);

        // If value is not null
        value = "Actual Value";

        // Prints: Actual Value
        System.out.println(Objects.requireNonNullElse(value, defaultValue));
    }
}

How It Works

  1. When value is null, Objects.requireNonNullElse(value, defaultValue) will safely return "Default Value".
  2. When value is not null, it returns the actual value of value.

Important Notes

  1. defaultObj cannot be null:
    If the defaultObj provided is null, the method will throw a NullPointerException. For example:

    String result = Objects.requireNonNullElse(null, null); // Throws NullPointerException
    
  2. Use for Non-Primitive Types Only:
    Since Objects.requireNonNullElse works only with reference types (i.e., not primitive types like int, double), use boxed primitives such as Integer, Double, etc., when needed.

    // Example with Integer:
    Integer number = null;
    Integer defaultNumber = 42;
    
    Integer result = Objects.requireNonNullElse(number, defaultNumber);
    
    // Prints: 42
    System.out.println(result);
    

Using Objects.requireNonNullElse is a clean, concise, and safe way to provide fallback values for potentially null objects without the need for verbose checks.