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:
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.
Do share your thoughts.
Hope this article helped. Happy learning... :)
- 05:42
- 2 Comments