Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a String to "" or leave it null?

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?

like image 360
cc. Avatar asked Nov 29 '22 20:11

cc.


1 Answers

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)) { ... }
like image 149
Gareth Davis Avatar answered Dec 05 '22 09:12

Gareth Davis