Java - String Empty Value Check


The length of an empty string is zero.

To test whether a String object is empty. There are three ways to check for an empty string:

  • Use the isEmpty() method.
  • Use the equals() method.
  • Get the length of the String and check if it is zero.

The following snippet of code shows how to use the three methods:

The second method is preferred as it handles the comparison with null gracefully.

The first and third methods throw a NullPointerException if the string is null.

The second method returns false when the string is null, for example, "".equals(null) returns false.


public class Main {
  public static void main(String[] args) {
    String str1 = "Hello";
    String str2 = "";

    // Using the isEmpty() method
    boolean empty1 = str1.isEmpty(); // Assigns false to empty1
    System.out.println(empty1);/*from  w  w  w  .  jav  a 2s  . c o m*/
    boolean empty2 = str2.isEmpty(); // Assigns true to empty1
    // Using the equals() method
    boolean empty3 = "".equals(str1); // Assigns false to empty3
    boolean empty4 = "".equals(str2); // Assigns true to empty4

    // Comparing length of the string with 0
    boolean empty5 = str1.length() == 0; // Assigns false to empty5
    boolean empty6 = str2.length() == 0; // Assigns true to empty6