StringUtils empty check

Background

In this Article , I will introduce ways to check if the Java String is empty or not.

My way to check empty string

We often would check if a String object is null or empty, so here is the code snippet

public static boolean isEmpty(String s) {
    return s==null||s.trim().length()==0;
}
public static boolean isNotEmpty(String s) {
    return !isEmpty(s);
}
/**
 * check if all params is empty
 */
public static boolean isNotEmpty(String ... params) {
    boolean foundEmpty = false;
    for(String param:params) {
        if(isEmpty(param)) {
            foundEmpty = true;
            break;
        }
    }
    if(!foundEmpty) {
        return true;
    }
    return false;
}

Other ways to check string empty

Certainly! In Java, there are several ways to check if a string is empty. Here are some common methods:

  1. Using the isEmpty() method: This method is available from Java 6 onwards and is a part of the String class.

    String str = "";
    if (str.isEmpty()) {
        System.out.println("The string is empty.");
    }
    
  2. Using the equals() method: This method compares the string with an empty string literal.

    String str = "";
    if (str.equals("")) {
        System.out.println("The string is empty.");
    }
    
  3. Using the length property: You can check if the length of the string is 0, which would mean it’s empty.

    String str = "";
    if (str.length() == 0) {
        System.out.println("The string is empty.");
    }
    
  4. Using trim() method: If you want to check for an empty string that may contain whitespace, you can trim the string first and then check its length.

    String str = "   ";
    if (str.trim().isEmpty()) {
        System.out.println("The string is empty or contains only whitespace.");
    }
    
  5. Using null check with equals(): If you’re also concerned about the string being null, you can check for that as well.

    String str = null;
    if (str == null || str.equals("")) {
        System.out.println("The string is null or empty.");
    }
    

Remember that null is not the same as an empty string (""). The isEmpty() method will not throw a NullPointerException if the string is null, whereas trying to call equals("") on a null reference will result in a NullPointerException. Always check for null before performing operations on a string if there’s a chance it could be null.