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 fornull.defaultObj: The object to return ifobjisnull. This cannot benull; otherwise, aNullPointerExceptionwill be thrown.
Returns
- If
objis notnull, it returnsobj. - If
objisnull, it returnsdefaultObj.
Key Features
- Ensures
defaultObjis nevernull. If you pass anulldefaultObj, the code will throw aNullPointerException. - 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
- When
valueisnull,Objects.requireNonNullElse(value, defaultValue)will safely return"Default Value". - When
valueis notnull, it returns the actual value ofvalue.
Important Notes
defaultObjcannot benull:
If thedefaultObjprovided isnull, the method will throw aNullPointerException. For example:String result = Objects.requireNonNullElse(null, null); // Throws NullPointerException- Use for Non-Primitive Types Only:
SinceObjects.requireNonNullElseworks only with reference types (i.e., not primitive types likeint,double), use boxed primitives such asInteger,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.
