isEmpty() String Example


java.lang.String class comes with many methods to check the string characters are lowercase or uppercase, digit or letter etc. Now, isEmpty() method returns true if string does not contain any characters or string length() is zero.

Following is the method signature.

  • public boolean isEmpty(): Tests string contains data. If the length() returns 0, then isEmpty() returns a boolean value of true. Introduced with JDK 1.6.

This method is useful in Web client-server programming where to know client entered any data in form field. request.getParameter().length()==0 can be replaced by request.getParameter().isEmpty().

Following example illustrates the usage of the above method.

public class StringMethodDemo
{
 public static void main(String args[])
 {
  String str1 = "";                            // empty string, no data
  String str2 = "ABCD";
  String str3 = null;
  
  boolean b1 = str1.isEmpty();
  boolean b2 = str2.isEmpty();

  System.out.println("String str1 does not contain data: "  + b1);  // true
  System.out.println("String str2 does not contain data: "  + b2);  // false

  System.out.println("String str3 does not contain data: "  + str3.isEmpty());  // false
 }
}

isEmpty()

The method throws NullPointerException on null string. See the code and screenshot.

Pass your comments and suggestions for improvement on this tutorial "isEmpty() String Example".

Leave a Comment

Your email address will not be published.