0
0
JavaHow-ToBeginner · 3 min read

How to Check Null or Empty String in Java Easily

In Java, you can check if a string is null or empty by using str == null || str.isEmpty(). This condition returns true if the string has no characters or is not initialized.
📐

Syntax

Use the following syntax to check if a string is null or empty:

  • str == null: checks if the string variable points to no object.
  • str.isEmpty(): checks if the string has zero characters.
  • Combine with || (OR) to check both conditions.
java
if (str == null || str.isEmpty()) {
    // string is null or empty
}
💻

Example

This example shows how to check if a string is null or empty and print a message accordingly.

java
public class CheckString {
    public static void main(String[] args) {
        String[] testStrings = {null, "", "Hello"};
        for (String str : testStrings) {
            if (str == null || str.isEmpty()) {
                System.out.println("String is null or empty");
            } else {
                System.out.println("String is: " + str);
            }
        }
    }
}
Output
String is null or empty String is null or empty String is: Hello
⚠️

Common Pitfalls

Common mistakes include calling isEmpty() on a null string, which causes a NullPointerException. Always check for null before calling isEmpty().

Wrong way:

if (str.isEmpty() || str == null) { ... }

Right way:

if (str == null || str.isEmpty()) { ... }
java
public class PitfallExample {
    public static void main(String[] args) {
        String str = null;
        // Wrong: causes NullPointerException
        // if (str.isEmpty() || str == null) {
        //     System.out.println("Null or empty");
        // }

        // Right:
        if (str == null || str.isEmpty()) {
            System.out.println("Null or empty");
        }
    }
}
Output
Null or empty
📊

Quick Reference

CheckCode ExampleDescription
Null checkstr == nullTrue if string is not assigned any object
Empty checkstr.isEmpty()True if string length is zero
Null or emptystr == null || str.isEmpty()True if string is null or empty
Null or blank (spaces)str == null || str.trim().isEmpty()True if string is null or only spaces

Key Takeaways

Always check for null before calling methods on a string to avoid errors.
Use str == null || str.isEmpty() to check if a string is null or empty.
Calling isEmpty() on a null string causes a NullPointerException.
Use str.trim().isEmpty() to check if a string is blank (only spaces).