The requireNonNull()
method in Java, part of the java.util.Objects
class, is used to check if a given object reference is not null
. If the object reference is null
, it throws a NullPointerException
with an optional custom message.
Table of Contents
- Introduction
requireNonNull()
Method Syntax- Understanding
requireNonNull()
- Examples
- Basic Usage
- Using a Custom Error Message
- Real-World Use Case
- Conclusion
Introduction
The requireNonNull()
method ensures that an object reference is not null
. This method is particularly useful for validating parameters in methods or constructors to ensure they are not null
, preventing potential NullPointerException
later in the code.
requireNonNull() Method Syntax
There are three overloaded versions of the requireNonNull()
method:
Basic Version
public static <T> T requireNonNull(T obj)
Version with Custom Error Message
public static <T> T requireNonNull(T obj, String message)
Version with Custom Error Message Supplier
public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier)
Parameters:
obj
: The object reference to be checked for nullity.message
: (Optional) The custom error message to include in theNullPointerException
.messageSupplier
: (Optional) A supplier that provides a custom error message.
Returns:
- The non-null object reference if it is not
null
.
Throws:
NullPointerException
: If the object reference isnull
.
Understanding requireNonNull()
The requireNonNull()
method validates that the specified object reference is not null
. If the reference is null
, it throws a NullPointerException
. This method is useful for early null checks to avoid null-related issues in the code.
Examples
Basic Usage
To demonstrate the basic usage of requireNonNull()
, we will validate an object reference.
Example
import java.util.Objects;
public class RequireNonNullExample {
public static void main(String[] args) {
String str = "hello";
// Ensures the object reference is not null
String nonNullString = Objects.requireNonNull(str);
System.out.println("Non-null string: " + nonNullString);
}
}
Output:
Non-null string: hello
Using a Custom Error Message
This example shows how to use requireNonNull()
with a custom error message.
Example
import java.util.Objects;
public class RequireNonNullWithMessageExample {
public static void main(String[] args) {
String str = null;
try {
// Throws NullPointerException with a custom message
String nonNullString = Objects.requireNonNull(str, "String cannot be null");
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
}
Output:
String cannot be null
Real-World Use Case
Validating Constructor Parameters
In a real-world scenario, you might use the requireNonNull()
method to validate parameters in a constructor, ensuring that mandatory fields are not null.
Example
import java.util.Objects;
public class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = Objects.requireNonNull(name, "Name cannot be null");
this.age = Objects.requireNonNull(age, "Age cannot be null");
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + '}';
}
public static void main(String[] args) {
try {
Person person = new Person(null, 25);
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
try {
Person person = new Person("Alice", null);
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
}
Output:
Name cannot be null
Age cannot be null
Conclusion
The Objects.requireNonNull()
method in Java provides a way to ensure that an object reference is not null
, throwing a NullPointerException
if it is. By using this method, you can validate critical parameters and avoid null-related issues early in your code.
Whether you are performing single or multiple null checks, the requireNonNull()
method offers a reliable way to handle nullity at runtime.
Comments
Post a Comment
Leave Comment