Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty String Validation

Tags:

java

string

null

I've read through this SO thread: Java, check whether a string is not null and not empty?

The question that arises (and was not answered in that thread), is:

Why is string.isEmpty() better than using string.equals("") ? In the same answer the poster states that prior to J6, people would use string.length == 0 as a way to check for empty strings. Am I missing something, because they all seem to do exactly the same thing... making it just a matter of beautifying your code.

like image 689
SnakeDoc Avatar asked Jan 28 '26 12:01

SnakeDoc


1 Answers

The best to use is

"".equals(yourString) 

as this avoids the null pointer exception.

If you use

string.equals("") 

and if your string is null, it will throw a null pointer exception.

and again the problem with isEmpty is that

It Returns true if, and only if, length() is 0

So if your string is empty it will also cause NPE.

like image 54
Juned Ahsan Avatar answered Jan 31 '26 01:01

Juned Ahsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!