Correct way to check empty string in JAVA

05:42

In our day-to-day programming activities, we usually come across multiple scenarios where we need to check whether a string is empty or not.

There are multiple ways to do this check in Java:
  1. equals method: str.equals(“”)
  2. length method: str.length() == 0  //recommended
  3. isEmpty method [From Java 1.6 onward]: str.isEmpty()  //recommended
The recommended way for empty string check is length() or isEmpty() method. We should never use equals(“”) for such a simple requirement.

Let’s have a look on the source code of String class to understand why we should use isEmpty/length:

length() method:
public int length() {
   return count;
}

isEmpty() method:
public boolean isEmpty() {
   return count == 0;
}

equals() method:
public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = offset;
            int j = anotherString.offset;
            while (n-- != 0) {
                if (v1[i++] != v2[j++])
                    return false;
            }
            return true;
        }
    }
    return false;
}

If we observe the source code of the above three methods provided by String class, it is very clear that length() is simply a getter method and returns length of the String. It’s obvious that any String having length 0 is always an empty string and so, the following code is able to detect whether the string is empty or not:
str.length() == 0;

The same reason holds behind using isEmpty() method. Moreover this method seems much verbose by its signature itself.

On the other hand, if we take a look on equals method, it seems to be relatively heavyweight. It does a lot of computation and consumes relatively more CPU cycles for the same operation. So, simply for such a basic check, using equals() method will result in lot of waste of CPU cycles.

Do share your thoughts.
Hope this article helped. Happy learning... :)

You Might Also Like

2 comments

  1. What if the string variable is null?

    ReplyDelete
    Replies
    1. Thanks for putting such a good point ChannelAdam.

      Btw, do we really need to check isEmpty()/length() for null strings...?
      length() and isEmpty() method will throw NPE for null strings. On the other hand equals() will return false for null input.
      We should always use length() and isEmpty() with/within guarded checks for null input.

      Delete