Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice - How to test if a string exists in Java?

Tags:

java

I render some data based on a condition. The backing method performs a check if a string exists. But I don't know if I can be happy with the compare to null?

public boolean isString(MyClass var) {
   return null != var.getMyString();
}

Could it be done better?

like image 815
membersound Avatar asked Dec 06 '25 02:12

membersound


2 Answers

I like StringUtils.isNotBlank() from Apache Commons Lang:

StringUtils.isNotBlank(var.getMyString())

It performs extra trim() which is desirable most of the time. If not, use StringUtils.isNotEmpty(). Another advantage: it uses CharSequence so you can pass String, StringBuilder, etc.

like image 157
Tomasz Nurkiewicz Avatar answered Dec 07 '25 19:12

Tomasz Nurkiewicz


You could do:

return var.getMyString() != null && !var.getMyString.isEmpty()
like image 23
Reverend Gonzo Avatar answered Dec 07 '25 19:12

Reverend Gonzo