notNull()
is a Validate
class that is used to check whether the passed object is null
or not.
null
, then the method raises an exception with a formatted message.null
, then the method returns the input as it is.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-lang
package, refer to the Maven Repository.
You can import the Validate
class as follows.
import org.apache.commons.lang3.Validate;
public static <T> T notNull(T object, String message, Object... values)
object
: The object to check if it is null
.message
: The exception message if the object is invalid.values
: The optional values for the formatted exception message.This method throws a NullPointerException
if the object is null
. Otherwise, it doesn’t return anything.
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();}}
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)
stringToValidate
= "hello"
The method returns the input value hello
as it is not a null
value.
stringToValidate
= null
exceptionMessageFormat
= "Argument should not be null"
The method throws a NullPointerException
as the input value is null
.
Free Resources