How to Check if String is Empty in Java: Simple Guide
In Java, you can check if a string is empty by using the
isEmpty() method, which returns true if the string has zero characters. Alternatively, you can check if string.length() == 0 to determine if it is empty.Syntax
The common ways to check if a string is empty in Java are:
string.isEmpty(): Returnstrueif the string length is zero.string.length() == 0: Checks if the string length equals zero.
Both methods require that the string is not null to avoid errors.
java
boolean isEmpty = string.isEmpty(); boolean isEmptyLength = (string.length() == 0);
Example
This example shows how to check if a string is empty using isEmpty() and length(). It also handles the case when the string is null to avoid errors.
java
public class CheckEmptyString { public static void main(String[] args) { String str1 = ""; String str2 = "Hello"; String str3 = null; System.out.println("str1 is empty: " + isEmptyString(str1)); System.out.println("str2 is empty: " + isEmptyString(str2)); System.out.println("str3 is empty: " + isEmptyString(str3)); } public static boolean isEmptyString(String s) { return s != null && s.isEmpty(); } }
Output
str1 is empty: true
str2 is empty: false
str3 is empty: false
Common Pitfalls
Common mistakes when checking if a string is empty include:
- Calling
isEmpty()orlength()on anullstring, which causes aNullPointerException. - Confusing empty strings (
"") withnullstrings. - Not trimming strings before checking, so strings with spaces are not considered empty.
Always check for null before calling methods on strings.
java
String s = null; // Wrong: causes NullPointerException // boolean empty = s.isEmpty(); // Right: check null first boolean emptySafe = (s != null && s.isEmpty());
Quick Reference
| Method | Description | Notes |
|---|---|---|
string.isEmpty() | Returns true if string length is zero | Throws NullPointerException if string is null |
string.length() == 0 | Checks if string length equals zero | Throws NullPointerException if string is null |
string == null || string.isEmpty() | Checks if string is null or empty | Safe to use to avoid errors |
string.trim().isEmpty() | Checks if string is empty or only spaces | Use to ignore whitespace-only strings |
Key Takeaways
Use
string.isEmpty() or string.length() == 0 to check if a string is empty.Always check if the string is
null before calling methods to avoid errors.Empty strings have zero characters;
null means no string object exists.Use
string.trim().isEmpty() to check for strings that are empty or only spaces.Avoid confusing empty strings with
null strings in your code logic.