What is StringUtils.isNotBlank in Java?

Overview

isNotBlank() is a static method of the StringUtils class that is used to check if a given string is not blank.

If a string does not satisfy any of the criteria below, then the string is considered to be not blank.

  1. The length of the string is zero or the string is empty.
  2. The string points to a null reference.
  3. The string contains only whitespace characters.

Note: A character can be classified as a whitespace character using the method Character.isWhitespace().

How to import StringUtils

StringUtils 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 StringUtils class as follows.


import org.apache.commons.lang3.StringUtils;

Syntax


public static boolean isNotBlank(final CharSequence cs)

Parameters

  • final CharSequence cs: the character sequence/string to be checked.

Return value

This method returns true if the string is not blank. Otherwise, it returns false.

Code

import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
String s = "543234asfg";
System.out.printf("The output of StringUtils.isNotBlank() for the string - '%s' is %s", s, StringUtils.isNotBlank(s));
System.out.println();
s = "";
System.out.printf("The output of StringUtils.isNotBlank() for the string - '%s' is %s", s, StringUtils.isNotBlank(s));
System.out.println();
s = null;
System.out.printf("The output of StringUtils.isNotBlank() for the string - '%s' is %s", s, StringUtils.isNotBlank(s));
System.out.println();
s = " \n\t";
System.out.printf("The output of StringUtils.isNotBlank() for the string - '%s' is %s", s, StringUtils.isNotBlank(s));
System.out.println();
}
}

Example 1

  • string - "543234asfg"

The method returns true, as the string is not null and not empty.

Example 2

  • string - ""

The method returns false, as the length of the string is zero.

Example 3

  • string - null

The method returns false, as the string points to a null reference.

Example 4

  • string - " \n\t"

The method returns false, as the string contains only whitespace characters.

Output

The output of the code will be as follows:


The output of StringUtils.isNotBlank() for the string - '543234asfg' is true
The output of StringUtils.isNotBlank() for the string - '' is false
The output of StringUtils.isNotBlank() for the string - 'null' is false
The output of StringUtils.isNotBlank() for the string - '    
	' is false

Free Resources