HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / String / Always Use length() Instead of equals() to Check Empty String

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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. NIRAJ PATEL

    September 21, 2016

    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..!
    🙂

  2. Pratap Shinde

    March 6, 2016

    That is a nice article, Lokesh.

    Thanks a lot

  3. sri

    November 9, 2014

    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..

    • Lokesh Gupta

      November 11, 2014

      If case sensitivity does not matter then initialize the strings like this:

      String s1 = &quot;Good Morning&quot;.toLowerCase();
      String s2 = &quot;Good Night&quot;.toLowerCase();
      
  4. ankit agrawal

    August 22, 2014

    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.

    • Lokesh Gupta

      August 22, 2014

      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.

    • Trejkaz

      March 26, 2019

      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.

  5. Rajendra J

    August 5, 2014

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

    • Lokesh Gupta

      August 5, 2014

      Thanks for sharing Rajendra.

  6. scott m gardner

    June 17, 2014

    Good information. Another option is the Guava Strings utilities class. https://guava.dev/releases/19.0/api/docs/com/google/common/base/Strings.html#isNullOrEmpty(java.lang.String)

  7. Nebu

    June 9, 2014

    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.

    • Lokesh Gupta

      June 9, 2014

      Thanks for your valuable feedback.

    • Nebu

      June 9, 2014

      That first paragraph (the one starting with “Whereas equals()…”) was intended to be quoted. I thought using the q tag would do that, but it seems like it’s showing up as if it was part of my response.

    • Hasan

      July 4, 2014

      I think it will still create arrays. It will not go in the while loop since the n is zero.

  8. sss

    February 24, 2014

    awesome info Lokesh…

  9. subbareddy

    November 30, 2013

    Useful information for every one………….

  10. baiyuxiong

    November 30, 2013

    Awesome post !

  11. Aparna

    August 5, 2013

    Basics explained very well…Thanks

  12. Anatol

    July 19, 2013

    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.

    • Lokesh Gupta

      July 19, 2013

      You are absolutely right. isEmpty() is now available in java 6 and java 7. Updating the post.

  13. GaaraCoder

    June 5, 2013

    Awesome information. Thank you.

  14. Shaique Ali

    April 2, 2013

    Very nice piece of information… Thanks Lokesh

Comments are closed on this article!

Search Tutorials

String methods

  • String concat()
  • String hashCode()
  • String contains()
  • String compareTo()
  • String compareToIgnoreCase()
  • String equals()
  • String equalsIgnoreCase()
  • String charAt()
  • String indexOf()
  • String lastIndexOf()
  • String intern()
  • String split()
  • String replace()
  • String replaceFirst()
  • String replaceAll()
  • String substring()
  • String startsWith()
  • String endsWith()
  • String toUpperCase()
  • String toLowerCase()

String examples

  • Convert String to int
  • Convert int to String
  • Convert String to long
  • Convert long to String
  • Convert CSV String to List
  • Java StackTrace to String
  • Convert float to String
  • String – Alignment
  • String – Immutable
  • String – StringJoiner
  • Java – Split string
  • String – Escape HTML
  • String – Unescape HTML
  • String – Convert to title case
  • String – Find duplicate words
  • String – Left pad a string
  • String – Right pad a string
  • String – Reverse recursively
  • String – Leading whitespaces
  • String – Trailing whitespaces
  • String – Remove whitespaces
  • String – Reverse words
  • String – Find duplicate characters
  • String – Check empty string
  • String – Get first 4 characters
  • String – Get last 4 characters
  • String – (123) 456-6789 pattern
  • String – Interview Questions

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces