Java Program to Check if a String is Empty or Null

1. Introduction

In Java, strings are objects that represent a sequence of characters. When working with strings, it's common to check if a string is empty (""), or if it is null (not pointing to any object). This is crucial for validating user input, avoiding NullPointerException, and ensuring data integrity. This blog post demonstrates how to check if a string is empty or null in Java, a fundamental task in both basic and advanced programming.

2. Program Steps

1. Declare and initialize a couple of string variables for testing.

2. Use conditional statements to check if the strings are null or empty.

3. Display appropriate messages based on the checks.

4. Repeat the process for different test cases.

3. Code Program

public class CheckString {
    public static void main(String[] args) {
        // Test strings
        String str1 = null;
        String str2 = "";
        String str3 = "Java";

        // Checking if str1 is null or empty
        if (str1 == null || str1.isEmpty()) {
            System.out.println("str1 is null or empty.");
        } else {
            System.out.println("str1 is not null or empty.");
        }

        // Checking if str2 is null or empty
        if (str2 == null || str2.isEmpty()) {
            System.out.println("str2 is null or empty.");
        } else {
            System.out.println("str2 is not null or empty.");
        }

        // Checking if str3 is null or empty
        if (str3 == null || str3.isEmpty()) {
            System.out.println("str3 is null or empty.");
        } else {
            System.out.println("str3 is not null or empty.");
        }
    }
}

Output:

str1 is null or empty.
str2 is null or empty.
str3 is not null or empty.

Explanation:

1. The program starts by declaring and initializing three string variables str1, str2, and str3 with different values for testing: null, an empty string, and a non-empty string, respectively.

2. It then checks each string to determine if it is null or empty using the conditional statement. The condition str == null || str.isEmpty() checks if the string is null or if its length is zero (empty). The isEmpty() method returns true if the string's length is 0.

3. Based on the evaluation of the condition, the program prints a message indicating whether each string is null or empty.

4. This approach allows for clear and concise checks for null or empty strings, which are common requirements in various programming scenarios, including input validation and data processing.

Comments