What is StringUtils.isWhitespace in Java?

isWhitespace() is a staticthe methods in Java that can be called without creating an object of the class. method of the StringUtils class that is used to check if the given character sequence or string contains only whitespace characters.

  • The method returns false if the input string is null.
  • The method returns true if the input string is empty.

How to import StringUtils

The definition of 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 isWhitespace(final CharSequence cs)

Parameters

final CharSequence cs: The character sequence/string to check.

Return value

This method returns true if the string contains only whitespace characters. Otherwise, it returns false.

Code

import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
// Example 1
String s = "hello-educative";
System.out.printf("The output of StringUtils.isWhitespace() for the string - '%s' is '%s'", s, StringUtils.isWhitespace(s));
System.out.println();
// Example 2
s = " \n \r\n";
System.out.printf("The output of StringUtils.isWhitespace() for the string - '%s' is '%s'", s, StringUtils.isWhitespace(s));
System.out.println();
// Example 3
s = "";
System.out.printf("The output of StringUtils.isWhitespace() for the string - '%s' is '%s'", s, StringUtils.isWhitespace(s));
System.out.println();
// Example 4
s = null;
System.out.printf("The output of StringUtils.isWhitespace() for the string - '%s' is '%s'", s, StringUtils.isWhitespace(s));
System.out.println();
}
}

Example 1

  • string = "hello-educative"

The method returns false because the string does not contain whitespace characters.

Example 2

  • string = " \n \r\n"

The method returns true because the string only contains whitespace characters.

Example 3

  • string = ""

The method returns true because the string is empty.

Example 4

  • string = null

The method returns false because the string is null.

Output

The output of the code will be as follows:


The output of StringUtils.isWhitespace() for the string - 'hello-educative' is 'false'
The output of StringUtils.isWhitespace() for the string - '   
 
' is 'true'
The output of StringUtils.isWhitespace() for the string - '' is 'true'
The output of StringUtils.isWhitespace() for the string - 'null' is 'false'

Free Resources

Attributions:
  1. undefined by undefined
  2. undefined by undefined