StringUtils isEmpty() and IsBlank() Example in Java

In this post, we are going to see about org.apache.commons.lang3.StringUtils isEmpty() and IsBlank() Example in Java. The isEmpty() method is used to check any string is empty or null. To check whitespace we can use IsBlank() method.

StringUtils isEmpty() Example in Java

Introduction.

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

pom.xml changes

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

 

StringUtils isEmpty() Example in Java.

The StringUtils isEmpty() is a static method which return type is boolean and accepts CharSequence as a parameter.

Syntax – public static boolean isEmpty(final CharSequence cs);
It returns true if any string is null or the length of the string is zero

Let’s see an isEmpty() Example in Java.

The output is –

true
true

The isEmpty() method doesn’t check for whitespace. It will return false if our string is whitespace.

The output is – false

We need to use StringUtils isBlank() method to check whitespace.

The internal implementation of the isEmpty method().

public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}

 

StringUtils isBlank() Example in Java.

The StringUtils isBlank() is a static method which return type is boolean and accepts CharSequence as a parameter.

Syntax – public static boolean isBlank(final CharSequence cs);
It returns true if any string is null or the length of the string is zero string is whitespace.

Let’s see an isBlank() Example in Java.

The output is –

true
true
true
false

 

The internal implementation of the StringUtils isBlank() method.

 

Note – The isBlank() has been changed from isBlank(String) to isBlank(CharSequence) in apache commons 3.0 versions.

Difference between StringUtils isEmpty() and isBlank() methods.

The output is –

Using StringUtils isEmpty() method
true
true
false
Using StringUtils isBlank() method
true
true
true

Note – The isEmpty() has been changed from isEmpty(String) to isEmpty(CharSequence) since apache commons 3.0 versions.

StringUtils isNotEmpty() Example in Java.

Let’s see an example of org.apache.commons.lang3.StringUtils.isNotEmpty() method example.

Output is –

false
false
true
true

Note – StringUtils.isNotEmpty() internally uses isEmty() method.

StringUtils isNotBlank() Example in Java.

Output is –

false
false
true
false

That’s all about StringUtils isEmpty() and IsBlank() Example in Java.

You may like.

See Docs here.

Summary – We have seen StringUtils isEmpty() and IsBlank() Example in Java. StringUtils isEmpty() returns true if string is empty or null. To check whitespace we can use isBlank() method. We also covered isNotEmpty() and isNotBlank() methods.

Top