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.
Basic Syntax
boolean isEmpty = str.isEmpty();
Java String isEmpty() method Examples
1. Checking if a String is Empty
public class Example{
public static void main(String args[]){
//empty string
String str1="";
//non-empty string
String str2="hello";
// Output: true
System.out.println(str1.isEmpty());
// Output: false
System.out.println(str2.isEmpty());
}
}
2. Checking if a string is null or empty
In the above example, we used isEmpty()
method to check if String is empty or not. However If you want to check whether the String is null or empty both then you can do it as shown in the following example. I have also covered this in this article: How to check if string is null, empty or blank.
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
3. Checking for Only Whitespace
Sometimes a string may contain whitespaces, in such cases you may want to check if a string is empty or contains only whitespace. For this purpose, you can use trim()
along with isEmpty()
.
public class Example{
public static void main(String args[]){
String str1 = " ";
String str2 = "text";
boolean isEmptyOrWhitespace1 = (str1.trim().isEmpty()); // true
boolean isEmptyOrWhitespace2 = (str2.trim().isEmpty()); // false
// Output: str1 is empty or whitespace: true
System.out.println("str1 is empty or whitespace: " + isEmptyOrWhitespace1);
// Output: str2 is empty or whitespace: false
System.out.println("str2 is empty or whitespace: " + isEmptyOrWhitespace2);
}
}
Summary
The String.isEmpty()
method is a simple method to check if a string is empty in Java. It is generally used along with trim()
method and null
checks to validate string content.
Leave a Reply