Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One step check for null value & emptiness of a string

Tags:

java

string

I have a setter method.

Then when another (say generate) method is run, I need to check the value of my fields. So in the case of String property, I need to know if it contains the value or if it was not set. So it may be null, "" or something meaningful, there are 3 possibilities. And it is rather boring to check first for a null value :

if (s != null)

then for an empty String

if (!s.isEmpty())

is there a one-step check here? You can tell me that I can initialize my String field with an empty String. [ IS IT COMMON? ] But what if someone passes a null value to the setter method setS? so do we always have to check if the Object value is null or not before doing something with that object?

Well, yes a setter method can check it's values and also a getter method can return a non-null value if the field is null. But is it the only solution? It 's too much work in getters & setters for a programmer to do!

like image 838
EugeneP Avatar asked Dec 16 '09 08:12

EugeneP


2 Answers

if(s != null && !s.isEmpty()){
// this will work even if 's' is NULL
}
like image 121
Ahmed Rezk Avatar answered Sep 28 '22 08:09

Ahmed Rezk


In the jakarta commons there is a StringUtils.isEmpty(String).

like image 22
DerMike Avatar answered Sep 28 '22 06:09

DerMike