Java String isEmpty() method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false. In other words you can say that this method returns true if the length of the string is 0.
Signature of isEmpty() method:
public boolean isEmpty()
Java String isEmpty() method Example
public class Example{ public static void main(String args[]){ //empty string String str1=""; //non-empty string String str2="hello"; //prints true System.out.println(str1.isEmpty()); //prints false System.out.println(str2.isEmpty()); } }
Output:
true false
Java String isEmpty() method Example to check if string is null or empty
As we have seen in the above example that isEmpty() method only checks whether the String is empty or not. If you want to check whether the String is null or empty both then you can do it as shown in the following example.
public class Example{ public static void main(String args[]){ String str1 = null; String str2 = "beginnersbook"; if(str1 == null || str1.isEmpty()){ System.out.println("String str1 is empty or null"); } else{ System.out.println(str1); } if(str2 == null || str2.isEmpty()){ System.out.println("String str2 is empty or null"); } else{ System.out.println(str2); } } }
Output:
String str1 is empty or null beginnersbook
Reference
String isEmpty() method – JavaDoc
Leave a Reply