What is Validate.notNull in Java?
notNull() is a Validate class that is used to check whether the passed object is null or not.
- If the passed object is
null, then the method raises an exception with a formatted message. - If the passed object is not
null, then the method returns the input as it is.
How to import Validate
The definition of Validate can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-langpackage, refer to the Maven Repository.
You can import the Validate class as follows.
import org.apache.commons.lang3.Validate;
Syntax
public static <T> T notNull(T object, String message, Object... values)
Parameters
object: The object to check if it isnull.message: The exception message if the object is invalid.values: The optional values for the formatted exception message.
Return value
This method throws a NullPointerException if the object is null. Otherwise, it doesn’t return anything.
Code
import org.apache.commons.lang3.Validate;public class Main{public static void main(String[] args){String stringToValidate = "hello";System.out.printf("Validate.notNull(%s) = %s", stringToValidate, Validate.notNull(stringToValidate));System.out.println();String exceptionMessageFormat = "Argument should not be null";stringToValidate = null;System.out.printf("Validate.notNull(%s) = %s", stringToValidate, Validate.notNull(stringToValidate, exceptionMessageFormat));System.out.println();}}
Output
The output of the code will be as follows:
Validate.notNull(hello) = hello
Exception in thread "main" java.lang.NullPointerException: Argument should not be null
at java.base/java.util.Objects.requireNonNull(Objects.java:347)
at org.apache.commons.lang3.Validate.notNull(Validate.java:224)
at Main.main(Main.java:12)
Explanation
Example 1
stringToValidate="hello"
The method returns the input value hello as it is not a null value.
Example 2
stringToValidate=nullexceptionMessageFormat="Argument should not be null"
The method throws a NullPointerException as the input value is null.
Free Resources
- undefined by undefined