tags:

views:

275

answers:

5

The title basically says it all. I'm usually testing this alongside a string == null, so I'm not really concerned about a null-safe test. Which should I use?

String s = /* whatever */;
...
if (s == null || "".equals(s))
{
    // handle some edge case here
}

or

if (s == null || s.isEmpty())
{
    // handle some edge case here
}

On that note - does isEmpty() even do anything other than return this.equals(""); or return this.length() == 0;?

A: 

It doesn't really matter. "".equals(str) is more clear (IMO).

isEmpty() returns count == 0;

Kylar
I'd say `str.isEmpty()` is much more clear than `"".equals(str)`. It reads as what you're checking. Matter of opinion though, I guess.
ColinD
I think some people prefer to do "".equals(str) to avoid NPE. I personally do not like it because I would rather check for the string to be not null first.
CoolBeans
+9  A: 

The main benefit of "".equals(s) is you don't need the null check (equals will check its argument and return false if it's null), which you seem to not care about. If you're not worried about s being null (or are otherwise checking for it), I would definitely use s.isEmpty(); it shows exactly what you're checking, you care whether or not s is empty, not whether it equals the empty string

Michael Mrozek
+1  A: 

One thing you might want to consider besides the other issues mentioned is that isEmpty() was introduced in 1.6, so if you use it you won't be able to run the code on Java 1.5 or below.

Fabian Steeg
That's definitely not a concern for me.
Matt Ball
+6  A: 

String.equals("") is actually a bit slower than just an isEmpty() call. Strings store a count variable initialized in the constructor, since Strings are immutable.

isEmpty() compares the count variable to 0, while equals will check the type, string length, and then iterate over the string for comparison if the sizes match.

So to answer your question, isEmpty() will actually do a lot less! and that's a good thing.

David Young
I think in this case the difference doesn't apply; there will never be an iteration over the strings for comparison, because the sizes won't match (unless the string actually is empty, and then there's no characters to iterate over)
Michael Mrozek
True but with equals you incur a reference check first to see if they are the same object, then an instanceof, then a cast to String, a length check, and then finally the iteration. If both Strings were empty then it would be just a simple reference check though.
David Young
I just wonder how can you compare both of those methods?
Truong Ha
source code to the String class is available http://www.java2s.com/Open-Source/Java-Document/6.0-JDK-Core/lang/java/lang/String.java.htm
David Young
+1  A: 

You can use apache commons StringUtils isEmpty() or isNotEmpty().

CoolBeans