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

Leave a Reply

19 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.