0
0
JavaHow-ToBeginner · 3 min read

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(): Returns true if 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() or length() on a null string, which causes a NullPointerException.
  • Confusing empty strings ("") with null strings.
  • 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

MethodDescriptionNotes
string.isEmpty()Returns true if string length is zeroThrows NullPointerException if string is null
string.length() == 0Checks if string length equals zeroThrows NullPointerException if string is null
string == null || string.isEmpty()Checks if string is null or emptySafe to use to avoid errors
string.trim().isEmpty()Checks if string is empty or only spacesUse 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.