Java String isEmpty() method returns true if the string length is 0, else returns false. This utility method was added to String class in Java 1.6 version.
Table of Contents
Java String isEmpty() Method Implementation
The internal implementation of isEmpty() method is:
public boolean isEmpty() {
return value.length == 0;
}
Java String isEmpty() Method Examples
Let’s look at some examples of using isEmpty() method.
1. String is empty
jshell> String s = "";
s ==> ""
jshell> s.isEmpty();
$54 ==> true
2. The string is not empty
jshell> String message = "Hello";
message ==> "Hello"
jshell> message.isEmpty();
$56 ==> false
3. String is null
If the string is null, calling isEmpty() method will throw NullPointerException.
jshell> String str = null;
str ==> null
jshell> str.isEmpty();
| Exception java.lang.NullPointerException
| at (#58:1)
Conclusion
Java String isEmpty() method comes handy when we have to check if the string is empty or not. It’s a very trivial operation and earlier we had to use length() method or write our own isEmpty() method implementation. That’s why this method has been added in the String class.