Set a String to "" or leave it null?
Solution 1
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.
Solution 2
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)) { ... }
cc.
Updated on June 14, 2022Comments
-
cc. almost 2 years
I have some String variables which are getting the values from invoking the function
getParameter()
and some of this variables will probably benull
.Later, I will evaluate this variables using
equals()
method. Should I set all the String variables to the empty String (""
) if they arenull
to avoid any problems? -
Rakesh Juyal over 14 yearsi prefer if ("hello".equals(variable))
-
Michael Rutherfurd over 14 yearsThe 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...