Check if a String is Empty or Null in Java — Definition, Examples and Program

Learn how to check whether a string is null or empty in Java. This blog explains the difference, common mistakes, examples, and a safe Java program with practice challenges.

Check if a String is Empty or Null in Java

In Java, checking whether a string is null or empty is extremely important. Many runtime errors occur when developers try to access methods on a null string.

Understanding the difference between null and an empty string helps you write safer and bug-free programs.

Difference Between Null and Empty String

Why Proper Checking is Important

Calling methods like length() or isEmpty() on a null string will cause a NullPointerException. Therefore, the null check must always come first.

How the Logic Works

  1. Check if the string is null.
  2. If not null, check if its length is zero.
  3. Decide whether the string is null, empty, or valid.

Example 1

Input: null

Result: String is Null

Example 2

Input: ""

Result: String is Empty

Example 3

Input: "Java"

Result: String is Not Empty

Java Program to Check if String is Null or Empty


import java.util.Scanner;

public class CheckNullOrEmpty {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a string (type nothing for empty): ");
        String str = sc.nextLine();

        if (str == null) {
            System.out.println("String is Null");
        } 
        else if (str.length() == 0) {
            System.out.println("String is Empty");
        } 
        else {
            System.out.println("String is Not Empty");
        }
    }
}

Sample Output


Enter a string (type nothing for empty):
String is Empty

Enter a string (type nothing for empty): Hello
String is Not Empty

Important Notes

Practice Challenges

  1. Modify the program to detect blank strings (only spaces).
  2. Check string emptiness without using length().
  3. Write a utility method that safely checks null and empty values.

Mastering null and empty string checks is essential for writing robust Java applications.