isEmpty()
is a static method of the StringUtils
class that is used to check if a given string is empty or not.
If a string satisfies any of the criteria below, then the string is considered to be empty.
null
reference.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 isEmpty(final CharSequence cs)
final CharSequence cs
: the character sequence/string to check.This method returns true
if the string is null
or the length of the string is zero; otherwise, it returns false
.
import org.apache.commons.lang3.StringUtils;public class Main {public static void main(String[] args) {String s = "543234";System.out.printf("The output of StringUtils.isEmpty() for the string - '%s' is %s", s, StringUtils.isEmpty(s));System.out.println();s = "";System.out.printf("The output of StringUtils.isEmpty() for the string - '%s' is %s", s, StringUtils.isEmpty(s));System.out.println();s = null;System.out.printf("The output of StringUtils.isEmpty() for the string - '%s' is %s", s, StringUtils.isEmpty(s));System.out.println();}}
The output of the code will be as follows.
The output of StringUtils.isEmpty() for the string - '543234' is false
The output of StringUtils.isEmpty() for the string - '' is true
The output of StringUtils.isEmpty() for the string - 'null' is true
string - "543234"
The method returns false
because the string is not null
and has a length greater than zero.
string - ""
The method returns true
because the length of the string is zero.
string - null
The method returns true
because the string points to a null
reference.