How to check if Java String is Empty or Null


To see if a String is empty or null, we should write an if condition by,

  • first, checking if the String object is null using the == operator.
  • second, checking if the its empty using the isBlank() function from the String class.

Note: It is important to check for null first before using methods like isBlank() on a string to ensure avoid potential NullPointerException.

Example:
import java.util.Arrays;
import java.util.stream.IntStream;

public class Example2 {

    public static void main(String[] args) {

        String name1 = "";
        String name2 = "Sam";
        String name3 = null;
        String name4 = " ";

        //Example 1:
        if (name1 == null || name1.isBlank()) {
            System.out.println("Name cannot be empty or null!");
        } else {
            System.out.println("Hello " + name1);
        }

        //Example 2:
        if (name2 == null || name2.isBlank()) {
            System.out.println("Name cannot be empty or null!");
        } else {
            System.out.println("Hello " + name2);
        }

        //Example 3:
        if (name3 == null || name3.isBlank()) {
            System.out.println("Name cannot be empty or null!");
        } else {
            System.out.println("Hello " + name3);
        }

        //Example 4:
        if (name4 == null || name4.isBlank()) {
            System.out.println("Name cannot be empty or null!");
        } else {
            System.out.println("Hello " + name4);
        }

    }
}
Output:

Name cannot be empty or null!
Hello Sam
Name cannot be empty or null!
Name cannot be empty or null!

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap