Monday, September 18, 2023

Right way to check if String is empty in Java with Example

What do most of us Java Programmers do while using String in Java? Check whether String is null or empty right? I am sure you know a couple of ways to test whether String is empty or not, but do you know the right way to do it? When we talk about Strings in Java, we can imagine them as arrays of characters, and they are, but in Java, they also object. An empty Java String is considered as the not null String that contains zero characters, meaning its length is 0. However, a Java String that might only contain the white-space character is not considered empty, it is considered to contain one character and its length is equal to 1. 

One of the most popular ways of checking whether String is empty or not is the String class' isEmpty() method, this looks perfect right, it's readable and returns boolean if String is empty otherwise returns false, but the problem is you can not call this method without checking whether String is null or not. In another word, this is not null safe and it will throw NullPointerException if String is null.

Another popular and faster way to check if String is empty or not is by checking its length like if String.length() = 0 then String is empty, but this is also not null safe. 

A third common way of checking the emptiness of String in Java is comparing it with empty String literal like "".equals(str), this method is not as fast as the previous two but it is null safe, you don't need to check for null, in case of null it will return false. So, in my opinion, this is the right way to check if the String is empty or not.  

If your definition of empty String also includes null then you can also use Apache Commons Lang's StringUtils class. It has methods like isEmpty() which return true for both null and empty string literal. Again this is also null safe and will not throw NullPointerException.

By the way, if you are new to Java Programming then I also suggest you check out a comprehensive Java course like The Complete Java Masterclass course by Tim Buchalka and his team on Udemy. This 80-hour long course is well structured and covers all essential Java concepts to learn Java from scratch. 




2 Null Safe way to Check if String is Empty or Not in Java

Here are a couple of examples of testing for String emptiness without worrying about null inputs. These are not the fastest way of checking emptiness but avoid additional null checks.

1. Using equals Method

As discussed in my tips to deal with NullPointerException, I have mentioned a technique to call the equals() method on a known String object instead of calling on an unknown object. This technique can be used to check the emptiness of String as well.

All you need to do is to call equals() method on empty String literal and pass the object you are testing as shown below :

String nullString = null;
String empty = new String();

boolean test = "".equals(empty);  // true
System.out.println(test);
        
boolean check = "".equals(nullString);    // false
System.out.println(check);

There will be no null pointers in this case.  Both of these ways confirm that String is not null and empty.




2. Using Apache Commons StringUtils class

If you are already using Apache commons then you can also use the isEmpty() method to check if String is empty or not. The only caveat here is that this method returns true in the case of null input as well, which may not be correct depending upon your application's definition of empty String. 

If you treat null as an empty string then you can use this wonderful null-safe method for a quick test, as shown in the following example :

boolean nullCheck = StringUtils.isEmpty(nullString);
boolean emptyCheck = StringUtils.isEmpty("");
        
System.out.println(nullCheck);   // true
System.out.println(emptyCheck);  // true


You can see that checking against the null String is opposite to how the equals method behaves. So use this method with caution. Since they return true even for null input, they cannot be trusted for tests like not null and empty. 

By the way, if you have to create an empty String, always use String literal "", it's more memory efficient. Since the String object is Immutable and can safely share between threads, there is no need to create multiple separate String objects, as String s = new String() will do, as shown in the following diagram. You can also see Core Java Made Easy course on Udemy to learn more about essential Java concepts. 

How to check if String is empty in Java



Right way to do Empty String check in Java

There are many ways to check if String is empty in Java, but what is the right way of doing it? right in the sense of robustness, performance, and readability.  If robustness is your priority then using the equals() method or Apache commons StringUtils is the right way to do this check. 

If you don't want to use the third-party library and are happy of doing a null check by yourself, then checking String's length is the fastest way, and using the isEmpty() method from String is the most readable way.

By the way,  don't confuse between empty and null String, if your application treats them the same, then you can consider them the same otherwise they are different, as null may not be classified as empty.  Here are three examples of checking String is empty or not by using the JDK library itself.

import java.util.Arrays;

/**
* Java Program to check if String is empty or not. There are many ways to do
* this but, but what is the right way?
*
* @author Javin Paul
*/
public class StringEmptyTest {

    public static void main(String args[]) {

        String nonEmpty = "This is non Empty String";
        String nullString = null;
        String emptyString = "";

        // Using isEmpty() method to check if String is empty in Java
        // need null check to avoid NullPointerException
        String[] inputs = {nonEmpty, nullString, emptyString};
        System.out.println("**** isEmpty() method Example *****");

        for (String s : inputs) {
            if (s != null) {
                System.out.println(String.format("Does String '%s' is empty? ",
                                  s) + s.isEmpty());
            }
        }

        // Using length() method to check if String is empty
        // for empty String length() == 0, require null check
        System.out.println("**** length() method Example *****");

        for (String s : inputs) {
            if (s != null) {
                System.out.println(String.format("Does String '%s' is empty? ",
                               s) + (s.length() == 0));
            }
        }

        // Using equals method to check if String is empty or not
        // this approach is null-safe and doesn't require null check
        // unlike previous examples.
        System.out.println("**** equals() method Example *****");
     
        for (String s : inputs) {
            System.out.println(String.format("Does String '%s' is empty? ", s) 
                          + "".equals(s));
        }

    }

}

Output:
Using isEmpty() method from java.lang.String to check emptiness
Does String 'This is non Empty String' is empty? false
Does String '' is empty? true
Does String 'This is non Empty String' is empty? false
Does String '' is empty? true
Does String 'This is non Empty String' is empty? false
Does String 'null' is empty? false
Does String '' is empty? true

If you are sure that the String you are checking is not null then use the length() method, it's the fastest way. If you give paramount importance to readability without compromising performance then String.isEmpty() is the right way to check String emptiness.



That's all about how to check if a String is empty in Java or not. As I said, if your preference is towards safety from NullPointerException then null safe methods are the best way to check emptiness like calling equals on empty String literal or using StringUtils.isEmpty() method from Apache Commons Lang. 

If you are already doing a null check and absolutely sure that the String you are checking is not null, use String.isEmtpy() method or simply length() method to check if the length of String is Zero.


Hungry for more, Here are amazing articles to explore String in Java :
Thanks for reading this article so far. If you like this Java tutorial and my explanation 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 are new to Java programming and looking for free online courses to learn Java from scratch then you can also see this Java Tutorial for Complete Beginners (FREE) course on Udemy. It's completely free and more than 1.2 million people have already joined this free course. 

And Now is the quiz time, what is your favorite way to check if String is empty in Java? 

7 comments:

  1. In Android we have TextUtils.isEmpty(String); which emulates the Apache StringUtils and it's usually a safe way to avoid NPEs.

    ReplyDelete
  2. First method is worst in term of Android Memory management.
    Always prefer TextUtils.isEmpty(String);

    ReplyDelete
  3. How about this?
    "if(str != null && !str.isEmpty())"

    ReplyDelete
  4. I have a already string object like String abs ="was";
    but I want to string object blank like String abs ="";
    how it is possible ?

    ReplyDelete
    Replies
    1. You already did that. assigning ="" will make it point to empty string object and abs=null means it will point to null

      Delete
  5. This website was... how do I say it? Relevant!! Finally I have found something which helped me.
    Thank you!

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.