Java · Technical

Java String – equals() vs length() to check empty string


In any kind of implementation, i (actually everyone) perform some empty string operation:

if(null != myString && !"".equals(myString))
    ...
}

.equals() method compare each character of strings to check the equality. In the example above we are:

  • Creating a String object (“”) with 0 length
  • using .equals() method to check if both strings are equal or not

Note: String class store values as char array

But when i had a look into the implementation of .equals() method, the idea comes in my mind why not use length() method in this scenario to save the .equals() overhead. length() method just return the length of string which String class store in count variable at the time we create String object. So its definition looks like:

public int length() {
    return count;
}

As simple as it can be. So i have simply replaced my code with length() metohd

if(null != myString && !0 == myString.length()) {
    ...
}

Is it safe to replace .equals() with .length() in my code?

It depends on your requirement actually, equals() method check for equality of two objects (string in our case), while .length() just return the number of characters in String object.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s