views:

306

answers:

2

I have some String variables which are getting the values from invoking the function getParameter() and some of this variables will probably be null.

Later, I will evaluate this variables using equals() method. Should I set all the String variables to the empty String ("") if they are null to avoid any problems?

+9  A: 

You have three options - If the item you are comparing too is known not to be null (e.g. a constant) then use that first.

if ("hello".equals(variable)) { ... }

Check for null first

if (variable != null && variable.equals("hello")) { ... }

Finally if null and the empty string can be considered the same down stream then set the string to the empty string. But if you wish to handle null differently then you can not do this.

mlk
i prefer **if ("hello".equals(variable))**
Rakesh Juyal
The syntax of the first option is "icky", I believe that is the technical term.The second option I'm not keen on as I've seen far too many programmers stuff up even simple boolean operations like that.Given a choice I go for StringUtils...
Michael Rutherfurd
+12  A: 

An alternative to is to use a static util method to do the compare. Apache commons-lang StringUtils.equals(String,String) is a possible with clearly defined behaviour for nulls.

// null safe compare
if (StringUtils.equals(variable,"hello")) {...}

// is "" or null 
if (StringUtils.isEmpty(variable)) { ... }

// with static imports it's a bit nicer
if (isNotEmpty(var1) && isEmpty(var2)) { ... }
Gareth Davis