![]() |
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Best way to check String Empty | |
boolean emptyString(String sample) | |
{ | |
return sample.length()==0; | |
} | |
// We should avoid this | |
boolean emptyString(String sample) | |
{ | |
return sample.equals(""); | |
} | |
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