Tuesday, June 23, 2015

Better way to check if String is empty: length() vs equals()


Empty?

It's quite a common and necessary thing to check if the string is empty or not. Different people use different things. Interviewer tries to check by giving you two ways to do it and ask you which one is better and why?

Let's see the two ways below, In fact we have isEmpty() function also, but interviewer is not interested in that.



On the face of it, both seems fine. Aren't they? So why is 2nd one not preferred way?

Simple. Check the Java code for equals() and length(). length() is simple and less time and memory. equals() takes more time and resources. 

length() just returns the count of characters. (isEmpty() also does length() == 0 check)
equals() used while loops, temporary arrays, typecasting and reference checks, which makes it unnecessary for this use case.



No comments:

Post a Comment