isWhitespace()
is a StringUtils
class that is used to check if the given character sequence or string contains only whitespace characters.
false
if the input string is null
.true
if the input string is empty.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;
public static boolean isWhitespace(final CharSequence cs)
final CharSequence cs
: The character sequence/string to check.
This method returns true
if the string contains only whitespace characters. Otherwise, it returns false
.
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();}}
"hello-educative"
The method returns false
because the string does not contain whitespace characters.
" \n \r\n"
The method returns true
because the string only contains whitespace characters.
""
The method returns true
because the string is empty.
null
The method returns false
because the string is null
.
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