Tuesday, September 14, 2021

5 ways to check if String is empty in Java - examples

String in Java is considered empty if it's not null and its length is zero. By the way, before checking length you should verify that String is not null because calling length() method on null String will result in java.lang.NullPointerException. Empty String is represented by String literal “”. The definition of empty String may be extended to those String as well which only contains white space but it's a specific requirement and in general String with white space is not considered as empty String in Java. Since String is one of the most frequently used classes and commonly used in method arguments, we often need to check if String is empty or not. Thankfully there are multiple ways to find if String is empty in Java or not.


You can also count the number of characters in String, as String is represented as a character array and decide if String is empty or not. If the count of characters is zero then its an empty String. In this Java String tutorial, we going to see 5 ways to find if any String in Java is empty or not. Here are our five ways to check empty String :

1) Checking if String is empty by using String.length()
2) Find  if String is empty by using equals() method of String
3) Checking if String is empty by using the isEmpty() method String, only available from Java 6 onwards.
4) Find if String is empty using Apache commons StringUtils class
5) Using Spring framework’s StringUtils.hasLength() method.

By the way, if you are new to the Spring framework then I also suggest you join a comprehensive and up-to-date course to learn Spring in depth. If you need recommendations, I highly suggest you take a look at these best Spring Framework courses which contain the most comprehensive and hands-on course to learn modern Spring. It' also the most up-to-date and covers Spring 5. It's also very affordable and you can buy in just $10 on Udemy sales which happen every now and then. 



1. Find if String is empty by checking the length

It's the easiest and popular method to verify if String is empty or not. You can find the length of String by calling the length() method which actually returns a number of characters in String. Be careful to check if String is null before calling length()to avoid NullPointerException. here is an example to check is String empty using length:

if(string != null && string.length() == 0){ return true; }




2. String empty using the equals method

You can also compare String to empty String literal "" to check if it’s empty or not. equals method in Java returns false if another argument is null, so it automatically checks for the null string as well. Here is a code example of checking emptiness of String using equals:

public static boolean isStringEmptyByEquals(String input){
        return "".equals(input);
}


3. Use isEmpty() method of Java 6

You can also check if the String is empty or not by using the isEmpty() method of the String class added in Java6. This is by far the most readable way but you need to check if String is null or not before calling the isEmpty() method. see code example section for use of isEmpty() method.

4. String Empty check using Apache Commons lang StringUtils

Apache commons-lang has a StringUtils class which has static utility method isEmpty(String input), which returns true if the input string is null or has a length greater than zero. Note this is different than our first method because it considers null as empty String while we are here only considering zero-length String as an empty String. 

If you are already using Apache commons-lang in your project e.g. for overriding the toString method, then you can use StringUtils instead of writing your own method. Check the example section to see how to use StringUtils.isEmpty(), by the way here is the output of StringUtils for some common input :

StringUtils.isEmpty("")        = true
StringUtils.isEmpty(null)      = true
StringUtils.isEmpty(" ")       = false
StringUtils.isEmpty("fix")     = false
StringUtils.isEmpty("  fix  ") = false


5. Check if String is Empty in Java - Using Spring

Spring is a popular Java framework and most of the new projects use Spring to take benefit of dependency Injection, it provides StringUtils class for performing common String operation. StringUtils provides a method called hasLength(input String), which returns true if the string is not null and contains any character, including white space. You can also use hasLength to determine if String is empty in Java or not. 

Next section has code examples of all five methods of checking empty string mentioned in this Java tutorial, by the way here is how hasLength() treats null and empty String :

StringUtils.hasLength("") = false
StringUtils.hasLength(null) = false
StringUtils.hasLength(" ") = true
StringUtils.hasLength("Hello") = true



Code Example to verify if String is empty in Java

How to check if String is empty in Java with ExampleHere is a complete code example of How to check if String is empty in Java. This program combines all approaches we have discussed so fart to check if Java The string is empty or not. One interesting thing to note in this program is How I have used StringUtils from Spring Framework. 

Since there are two classes with the same name but from different packages, i.e. StringUtils from Apache and Spring. You can only import one and you need to use others with its fully qualified name to avoid ambiguity.

import org.apache.commons.lang.StringUtils;

public class StringEmptyTest {

    public static void main(String args[]) {
 
        String input1 = "";
        String input2 = null;
        String input3 ="abc";
     
        //determine if String is empty using length method , also checks if string is null
        System.out.println("checking if String empty using length");
        System.out.println("String " + input1 + " is empty :" +isStringEmpty(input1) );
        System.out.println("String " + input2 + " is empty :" +isStringEmpty(input2) );
        System.out.println("String " + input3 + " is empty :" +isStringEmpty(input3) );
     
        //determine if String is empty using equals method
        System.out.println("find if String empty using equals");
        System.out.println("String " + input2 + " is empty :" +isStringEmptyByEquals(input2) );
     
         //determine if String is empty using isEmpty of Java 6
        System.out.println("find if String empty using isEmpty method of Java 6");
        System.out.println("String " + input3 + " is empty :" + input3.isEmpty());
     
        //determine if String is empty by Apache commons StringUtils
        System.out.println("check if String empty by commons StringUtils");
        System.out.println("String " + input2 + " is empty :" + StringUtils.isEmpty(input2));
     
        //determine if String is empty by Spring framework StringUtils hasLength method
        System.out.println("check if String empty by Spring framework StringUtils");
        System.out.println("String " + input2 + " is empty :" + org.springframework.util.StringUtils.hasLength(input2));

     
    }
 
    public static boolean isStringEmpty(String input){
        if(input != null && input.length() == 0){
            return true;
        }
        return false;
    }
 
    public static boolean isStringEmptyByEquals(String input){
        return "".equals(input);
    }
}

Output:
checking if String empty using length
String  is empty :true
String null is empty :false
String abc is empty :false

find if String empty using equals
String null is empty :false

find if String empty using isEmpty method of Java 6
String abc is empty :false

check if String empty by commons StringUtils
String null is empty :true

check if String empty by Spring framework StringUtils
String null is empty :false


That’s all on How to check if String is empty in Java. I thing Java 6 isEmpty() method is more readable than any other option but it’s not null safe which means either write your own method or use hasLength() from Spring Framework.  By the way, be careful with null String as some programmers consider null string as empty String and even Apache commons StringUtils.isEmpty() method return true for null String.


Related Java String Tutorials and Questions from Javarevisited Blog
That's all about how to check if the given String is empty in Java or not. If you like this Java tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note. 

P.S. - If you want to learn how to develop RESTful Web Service using Spring MVC in-depth, I suggest you join the REST with Spring certification class by Eugen Paraschiv. One of the best courses to learn REST with Spring MVC. 

10 comments:

  1. I don't think using StringUtils from Spring framework should be considered best practice, because in their documentation is:

    Mainly for internal use within the framework; consider Jakarta's Commons Lang for a more comprehensive suite of String utilities.

    see: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/util/StringUtils.html

    ReplyDelete
  2. I also prefer using apache's StringUtils isBlank() and isNotBlank().

    ReplyDelete
  3. @Anonymous, isBlank() and isNotBlank() is also a good choice but they return true even if String contains whitespace, i.e. they are not empty or you can say when length of String is not zero. If your definition of empty String is equal to blank i.e. include white space than isBlank() is a real good choice.

    StringUtils.isBlank(null) = true
    StringUtils.isBlank("") = true
    StringUtils.isBlank(" ") = true

    ReplyDelete
  4. I recommend Guava and its class com.google.common.base.Strings. It contains methods isNullOrEmpty(String string). Full docs here:
    http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Strings.html#isNullOrEmpty(java.lang.String)

    ReplyDelete
  5. Another option to StringUtils.isBlank(" "); could be " ".trim().length() == 0

    ReplyDelete
  6. What is difference between empty String and blank String?

    ReplyDelete
  7. I have used your first example thousands of times,
    if(string != null && string.length() == 0){ return true; }

    I got burned. The string was all whitespace (and had length > 0). I recommend removing the whitespace before checking the length using the String trim() method
    ,
    if(string != null && string.trim().length() == 0){ return true; }

    ReplyDelete
  8. @Anonymous, that's true, the length() will return non-zero value for String containing only space, if you consider it empty, which many of us do, then trim() is the right option. In SQL, you need to both rtrim() and ltrim(), thank god, Java trim() removes both leading and trailing space :-)

    ReplyDelete
  9. Why does if(char z=="") does not work?
    Give some condition to check the blank in string

    ReplyDelete
  10. Hello Ranjit, it doesn't work because "" is a String and not character.

    ReplyDelete