🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment