Set a String to "" or leave it null?

10,096

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)) { ... }
Share:
10,096
cc.
Author by

cc.

Updated on June 14, 2022

Comments

  • cc.
    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 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?

  • Rakesh Juyal
    Rakesh Juyal over 14 years
    i prefer if ("hello".equals(variable))
  • Michael Rutherfurd
    Michael Rutherfurd over 14 years
    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...