Set string to "" or leave it blank?

I have some String variables that get values ​​from a call to getParameter() , and some of these variables are likely to be null .

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

+4
source share
2 answers

You have three options: If the element you are comparing is also known as non-zero (like a constant), then use this first.

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

Check null first

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

Finally, if null and the empty string can be considered the same thread down, then set the string to the empty string. But if you want to handle null differently, you cannot do this.

+10
source

An alternative is to use the static util method for comparison. Apache commons-lang StringUtils.equals (String, String) is possible with well-defined behavior for zeros.

 // null safe compare if (StringUtils.equals(variable,"hello")) {...} // is "" or null if (StringUtils.isEmpty(variable)) { ... } // with static imports it a bit nicer if (isNotEmpty(var1) && isEmpty(var2)) { ... } 
+13
source

All Articles