StringUtils isWhitespace() example in Java

In this post, we will see org.apache.commons.lang3.StringUtils isWhitespace() example in Java. The isWhitespace() method is used to check given character is a space or not. It returns true if the given character is only space else returns false.

We need to add the below dependency in maven to use org.apache.commons.lang3.StringUtils isWhitespace() method. We can download the apache-commons maven dependency from here.

Note – The StringUtils class provides a different method containsWhitespace() to check string contains whitespace or not.

pom.xml changes

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>

Syntax of StringUtill.isWhiteSpace() method

public static boolean isWhitespace(final CharSequence cs)

StringUtils isWhitespace() Example in Java

package com.javatute;

import org.apache.commons.lang3.StringUtils;

public class StringUtilsIsWhitespace {
    public static void main(String[] args) {
        System.out.println(StringUtils.isWhitespace(null));//false
        System.out.println(StringUtils.isWhitespace("f21"));//false
        System.out.println(StringUtils.isWhitespace("21"));//false
        System.out.println(StringUtils.isWhitespace("jbl"));//false
        System.out.println(StringUtils.isWhitespace(" "));//true
        System.out.println(StringUtils.isWhitespace("java "));//false
        System.out.println(StringUtils.isWhitespace(""));//true

    }
}

Output is

false
false
false
false
true
false

Few questions related to whitespace.

How to remove spaces using apache StringUtils?

The apache StringUtils provides StringUtils.deleteWhitespace(CharSequence cr) a method to delete whitespace from String.

How to check if any string contains whitespace in Java?

The StringUtils provides StringUtils.containsWhitespace() a method to check string contains whitespace or not. We can also use s1.contains(" ") to check string contains whitespace or not.

public class StringWhiteSpaceCheck{
    public static void main(String[] args) {
        String s1 = "java ";
        System.out.println(s1.contains(" "));//true
    }
}

Output is

true

See StringUtils isWhitespace() docs.

That’s all about StringUtils isWhitespace() example in Java.

Related post.