Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (10.2k points)

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;?

1 Answer

0 votes
by (46k points)

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

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...