What is StringUtils.containsWhitespace in Java?

Overview

containsWhitespace is a static method of the StringUtils class that is used to check whether a string contains any whitespace or not. A character is classified as whitespace with the help of Character.isWhitespace.

StringUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added 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>

Note: For other versions of the commons-lang package, refer to Maven Repository.

The StringUtils class can be imported as follows:

import org.apache.commons.lang3.StringUtils;

Syntax

public static boolean containsWhitespace(final CharSequence seq)

Parameters

This method takes one parameter, final CharSequence seq, the Character Sequence/String to be checked for whitespace.

Returns

This method returns true if there is whitespace in the string and false otherwise.

Examples

In the code below, we define different strings with and without whitespace characters. Next, the containsWhitespace function is used to check whether the strings contain whitespace characters or not.

import org.apache.commons.lang3.StringUtils;
public class Main{
public static void main(String[] args){
String text1 = "educative educative";
String text2 = "educative \t educative";
String text3 = "educative \n educative";
String text4 = "educativeeducative";
System.out.println(StringUtils.containsWhitespace(text1));
System.out.println(StringUtils.containsWhitespace(text2));
System.out.println(StringUtils.containsWhitespace(text3));
System.out.println(StringUtils.containsWhitespace(text4));
}
}