notBlank()
is a Validate
class that is used to check that the specified argument character sequence is not null
,
Otherwise, the method throws an exception with the specified message.
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 extends CharSequence> T notBlank(final T chars, final String message, final Object... values)
final T chars
: This is the character sequence to check.
final String message
: This is the exception message.
final Object... values
: These are the optional values for the formatted exception message.
This method returns the character sequence if the passed character sequence is not blank.
import org.apache.commons.lang3.Validate;public class Main{public static void main(String[] args){// Example 1String stringToValidate = "hello";System.out.println("Validate.notBlank(stringToValidate) = " + Validate.notBlank(stringToValidate));// Example 2String exceptionMessageFormat = "Argument should not be null/empty/whitespace";stringToValidate = "";System.out.println("Validate.notBlank(stringToValidate) = " + Validate.notBlank(stringToValidate, exceptionMessageFormat));}}
object to validate = "hello"
The method returns the input value hello
, as it’s not null
, empty, or whitespace.
object to validate = ""
exception message = "Argument should not be null/empty/whitespace"
The method throws an IllegalArgumentException
, as the input value is empty.
The output of the code will be as follows:
Validate.notBlank(stringToValidate) = hello
Exception in thread "main" java.lang.IllegalArgumentException: Argument should not be null/empty/whitespace
at org.apache.commons.lang3.Validate.notBlank(Validate.java:441)
at Main.main(Main.java:11)