Core Java >> Strings
Best way to check for an empty string
There are multiple ways to find if a string is empty in Java. Even some String utility also provide helper methods to check is the string is empty. By empty string we mean the contents of the string is blank (which is same as “”).
The following program shows how the API methods can be used to check is a string object is empty or not.
package com.example;
/** This class is a Java tutorial for finding empty string
*
* @author Extreme Java
*/
public class Test{
/** This method shows how to check if a string is empty
*
* @param args
*/
public static void main(String[] args) {
String str="";
//check empty string by using == operator
if(str == "") {
System.out.println("Blank String 1");
}
//check empty string by using equals method
if(str.equals("")) {
System.out.println("Blank String 1");
}
//check empty string by using length method
if(str.length() ==0 ) {
System.out.println("Blank String 1");
}
String str2 = new String("");
//check empty string by using == operator
if(str2 == "") {
System.out.println("Blank String 2");
}
//check empty string by using equals method
if(str2.equals("")) {
System.out.println("Blank String 2");
}
//check empty string by using length method
if(str2.length() ==0 ) {
System.out.println("Blank String 2");
}
}
}
output:
Blank String 1
Blank String 1
Blank String 1
Blank String 2
Blank String 2
As the output above shows, the string literal can be checked for emptiness either by using the equals method or the == operator and both the methods return valid results.
But the == operator used with string objects created with new operator will not return valid results for empty check on strings.
The length method can be used safely with any kind of string objects to check if it is empty or not.
Other Java Tutorial
Custom Exceptions in Java
Java Custom Exceptions
Disadvantage of Exception Handling in Java
Comments
Mitch
I usually check this with:
if (str == null || str.isEmpty()) {
…
}
Also commons-lang provides isEmpty() and isBlank() methods in its StringUtils class
Andrea
but str.lenght() is not safety for null, like isEmpty()..
So, from now, i’ll prefer equals every time in this way: “”.equals(str)
Second question, the example you wrote is not clear, how can i know wich ‘Blank String 2′ is not been printed?
..but thanks, i didn’t know about this issue that you presented. :)
admin
@Andrea
There is description at the end of program which says which sysout didn’t got printed successfully.



olgo
I disagree.
You should not rely on == when comparing strings (http://www.zparacha.com/java-string-comparison/).
AFAIK str.equals(“”) creates unnecessary string instance just to be thrown away after comparison.
So if there is a reason to not use isEmpty(), length()==0 should be used instead.