What is StringUtils.isWhitespace in Java?
isWhitespace() is a StringUtils class that is used to check if the given character sequence or string contains only whitespace characters.
- The method returns
falseif the input string isnull. - The method returns
trueif 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-langpackage, 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 1String 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 2s = " \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 3s = "";System.out.printf("The output of StringUtils.isWhitespace() for the string - '%s' is '%s'", s, StringUtils.isWhitespace(s));System.out.println();// Example 4s = 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
- undefined by undefined
- undefined by undefined