AppDividend
Latest Code Tutorials

Java String isEmpty() Function Example

0

A situation that arises while solving many algorithmic problems or while development is determining when a String is empty, i.e., has size 0. To determine this, the String class (Java.lang.String), since the issue of JDK 1.6, has an in-built method isEmpty(). This method, as mentioned above, checks whether a String is empty or non-empty.

Java String isEmpty()

Java string isEmpty() method checks if this string is empty or not. It returns true if the length of the string is 0 otherwise false. In other words, true is returned if the string is empty otherwise it returns false.

 

Java String isEmpty()

Internal implementation

public boolean isEmpty() {  
  return value.length == 0;  
}

Syntax: public boolean isEmpty()

This method will return true if the string is empty and will return false otherwise.

The following examples demonstrate the use of this method:

See the following code.

public class Example1 {
  public static void main(String[] args) {
    String str1 = "abc";
    System.out.println(str1.isEmpty());
  }
}

Output

 

Java String isEmpty() Function

In the above example, the object of Class String – str1, has been initialized to contain the value “abc”, therefore, it has size 3 and is non-empty. So when the isEmpty() method is used, it returns false.

On the contrary, consider the following example where the reverse happens.

public class Example2 {
  public static void main(String[] args) {
    String str1 = "";
    System.out.println(str1.isEmpty());
  }
}

Output

 

Java String isEmpty() Function Example Tutorial

In the above example, str1 has been initialized as an empty String, and therefore, when the isEmpty() method is called, it returns true

The next example demonstrates the use of the isEmpty() method in the context of control flow statements:

See the following code.

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

    if (str1.isEmpty()) {
      System.out.println("String 1 is empty.");
    }

    if (str2.isEmpty()) {
      System.out.println("String 2 is empty.");
    }
  }
}

Output

 

Java String isEmpty() Tutorial

In the above example, the condition in both of the if statements will evaluate to true only if the said String is empty. Therefore, since the only str1 is empty and not str2, the first if block is executed while the second is skipped.

Conclusion

Java String isEmpty() String method checks whether a String is empty or not.

Finally, Java String isEmpty() Function Example is over.

Related Posts

Java String lastIndexOf()

Java String startsWith()

Java String split()

Java String join()

Java String replace()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.