What is Validate.notBlank() in Java?

notBlank() is a staticthe methods in Java that can be called without creating an object of the class. method of the Validate class that is used to check that the specified argument character sequence is not null, a length of zerono characters, empty, or whitespace.

Otherwise, the method throws an exception with the specified message.

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-lang package, refer to the Maven Repository.

You can import the Validate class as follows.


import org.apache.commons.lang3.Validate;

Syntax


public static <T extends CharSequence> T notBlank(final T chars, final String message, final Object... values)

Parameters

  • 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.

Return value

This method returns the character sequence if the passed character sequence is not blank.

Code

import org.apache.commons.lang3.Validate;
public class Main{
public static void main(String[] args){
// Example 1
String stringToValidate = "hello";
System.out.println("Validate.notBlank(stringToValidate) = " + Validate.notBlank(stringToValidate));
// Example 2
String exceptionMessageFormat = "Argument should not be null/empty/whitespace";
stringToValidate = "";
System.out.println("Validate.notBlank(stringToValidate) = " + Validate.notBlank(stringToValidate, exceptionMessageFormat));
}
}

Explanation

Example 1

  • object to validate = "hello"

The method returns the input value hello, as it’s not null, empty, or whitespace.

Example 2

  • object to validate = ""
  • exception message = "Argument should not be null/empty/whitespace"

The method throws an IllegalArgumentException, as the input value is empty.

Output

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)

Free Resources