Understanding the Difference Between Null and Empty String
In Groovy, there is a subtle difference between a variable whose value is null and a variable whose value is the empty string.
The value null represents the absence of any object, while the empty string
is an object of type String with zero characters. If you try to compare the
two, they are not the same.
For example, any code inside the following conditional block will not execute because the
value of varA (null) does not equals the value of varB (the
empty string).
def varA = null
def varB = '' /* The empty string */
if (varA == varB) {
// Do something here when varA equals varB
}
Another common gotcha related to this subtle difference is that trying to compare a variable
to the empty string does not test whether it is null. For example, the
code inside the following conditional block will execute (and cause a
NullPointerException at runtime) because the null value of
varA is not equal to the empty string:
def varA = null
if (varA != '') {
// set varB to the first character in varA
def varB = varA.charAt(0)
}
To test whether a string variable is neither null nor empty, you
could explicitly write out both conditions like this:
if (varA != null && varA != '') {
// Do something when varA is neither null nor empty
}
However, Groovy provides an even simpler way. Since both null and the empty
string evaluate to false when interpreted as a boolean, you can use the
following instead:
if (varA) {
// Do something when varA has a non-null and non-empty value
}
If varA is null, the condition block is skipped. The same
will occur if varA is equal to the empty string because either condition will
evaluate to boolean false. This more compact syntax is the recommended
approach.