Always Use length() Instead of equals() to Check Empty String

In your day-to-day programming activities, you must be coming across multiple situation where you need to check if a string is empty. There are various ways to do this and some use string1.equals(“”). NEVER do this.

Best way to check if string is empty or not is to use length() method. This method simply return the count of characters inside char array which constitutes the string. If the count or length is 0; you can safely conclude that string is empty.

public boolean isEmpty(String str)
{
    return str.equals("");        //NEVER do this
}

public boolean isEmpty(String str)
{
    return str.length()==0;        //Correct way to check empty
}

If you want to know the reason then continue reading further.

Lets see the source code of both methods inside String.java class.

Method length()

public int length() {
	return count;
}

Method equals()

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;
}

Analysis

As you can see that length() method is simply a getter method which return the count of characters in array. So it practically does not waste much CPU cycles to compute the length of string. And any String with length 0 is always going to be empty string.

Whereas equals() method takes a lot of statements before concluding that string is empty. It does reference check, typecasting if necessary, create temporary arrays and then use while loop also. So, its lot of waste of CPU cycles to verify a simple condition.

Do let me know if you think otherwise.

Update: From java 6 onwards, isEmpty() function is available in String class itself. Please use this function directly.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

22 thoughts on “Always Use length() Instead of equals() to Check Empty String”

  1. You are true except.. You said every time it creates array.. It does not create an array in all cases.. it creates array only if length of both strings are matching.. which would not be the case when you compare it like equals(“”)
    Nice Article..!
    🙂

    Reply
  2. Hi

    I have two Strings.I want to find the common letters in both the strings.Here is my code .My output should be (G,o,od,n,i,g)

    String s1 = “Good Morning”;
    String s2 = “Good Night”;
    String commonChars = “”;

    for (int i = 0; i < s1.length(); i++) {
    char chr = s1.charAt(i);
    if (s2.indexOf(chr) != -1) {
    commonChars = commonChars + chr;
    }
    }
    System.out.println("The common chars are : "+ commonChars);
        }

    After i compiled the above program iam not getting the expected output am getting (G,o,od,i,g).It is not displaying 'n' character because in the S2 'N' is capital that's y it is not displaying .Can any one please resolve this one and please tell me how to display the same outpout using collections ?

    Thanks Advacnce..

    Reply
  3. Apache gives us reformed way of this by StringUtils.isBlank(String str). It provides 3 checks: null, whitespace and empty. As generally we require all these 3 checks so this is another option.

    Then we have Strings.isNullOrEmpty(String string) from google guava but it gives null and empty check only; so this is another option if we don’t want whitespace check.

    Reply
    • Hi Ankit, You are completely true. But if your project does not require these libs for any other tasks then adding them for only checking empty string is not a good idea.
      And the intent of post is to compare performance only.

      Reply
    • isBlank is problematic anyway.

      First of all, it imposes one person’s opinion (whoever wrote the commons library method) on what is considered whitespace, which probably doesn’t agree with what the user considers whitespace. This enters a discussion about i18n, since many of the characters which are debatable turn out to be edge case characters used in specific scripts.

      Ignoring that, though, even if you did actually care about blankness, the check for blank essentially works like this:

      * If it’s null, then it’s blank
      * If it’s not null, trim it – it’s blank iff it’s now empty
      * Trim the string and use it

      But hang on, now there is a risk of forgetting to trim it when you get back from the blank check. So you would end up wanting to do it like this instead:

      * If it’s null, then set it to empty. Or tell the person handing you the string not to use nulls, because nulls are bad and anyone who uses them should feel bad.
      * Now it’s not null. Trim it.
      * Check for empty.
      * If the string wasn’t empty, use it.

      It’s very hard to imagine a case where you would want to trim the string only when checking whether it’s blank, and then not trimming it when you actually use it.

      Reply
  4. Hi folks,

    Apache String utility is using following code, please have a look into it.

    /**
    * Checks if a String is whitespace, empty (“”) or null.
    *
    *
    * StringUtils.isBlank(null) = true
    * StringUtils.isBlank(“”) = true
    * StringUtils.isBlank(” “) = true
    * StringUtils.isBlank(“bob”) = false
    * StringUtils.isBlank(” bob “) = false
    *
    *
    * @param str the String to check, may be null
    * @return true if the String is null, empty or whitespace
    * @since 2.0
    */
    public static boolean isBlank(String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
    return true;
    }
    for (int i = 0; i < strLen; i++) {
    if ((Character.isWhitespace(str.charAt(i)) == false)) {
    return false;
    }
    }
    return true;
    }

    /**
    * Checks if a String is not empty (“”), not null and not whitespace only.
    *
    *
    * StringUtils.isNotBlank(null) = false
    * StringUtils.isNotBlank(“”) = false
    * StringUtils.isNotBlank(” “) = false
    * StringUtils.isNotBlank(“bob”) = true
    * StringUtils.isNotBlank(” bob “) = true
    *
    *
    * @param str the String to check, may be null
    * @return true if the String is
    * not empty and not null and not whitespace
    * @since 2.0
    */
    public static boolean isNotBlank(String str) {
    return !StringUtils.isBlank(str);
    }

    Reply
  5. Whereas equals() method takes a lot of statements before concluding that string is empty. It does reference check, typecasting if necessary, create temporary arrays and then use while loop also.

    Actually, it only performs a reference check and a instanceof check. It will not create a temporary array and it will not use a while loop, because the condition if (n == anotherString.count) { will be false.

    Also, a good reason to prefer "".equals(yourString) over yourString.length() == 0 is that the former won’t throw a NullPointerException if yourString is null, while the latter will.

    I strongly recommend using "".equals(yourString) by default, and only use yourString.length() == 0 (or yourString != null && yourString.length() == 0) if you perform profiling on your code and have determined that "".equals(yourString) is the bottleneck in your code.

    Otherwise, you are introducing bugs in exchange for speeding up the parts of your code which don’t need to be sped up.

    Reply
  6. Thank you for the useful information. But I think it makes sense to mentioning about the method isEmpty(), which is present in the String-class since Java 6 and also checks the count of characters in array. But this solution is not appropriate, if it’s necessary to support previous versions of Java.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.