Checking if a String is empty


Since Java 6 there is a new way to check if a String is empty. The most common way to determine if a String is empty is to call the length() method of the String class and check if it returns 0.
There is now a method added to the class called isEmpty() which returns a boolean value.

The output from the code below is:

true
true

false
false



/**
 *
 * @author javadb.com
 */

public class Main {
    
    /**
     * Example method for checking if a String is empty
     */

    public void checkEmptyString() {
        
        String a1 = "";
        String b1 = "not an empty string";
        
        System.out.println("Checking a1 the new way: " + a1.isEmpty());
        System.out.println("Checking a1 the old way: " + (a1.length() == 0));
        
        System.out.println();
    
        System.out.println("Checking b1 the new way: " + b1.isEmpty());
        System.out.println("Checking b1 the old way: " + (b1.length() == 0));
    }
    
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().checkEmptyString();
    }
}





   What kind of Java example would you like to see on this site?

   
     E-mail (optional)