Consider member variable:
String foo;
I only want to call setFoo
if foo
has not previously been set or currently is empty.
For this purpose, I am not sure if this is sufficient:
if(foo==null || foo.isEmpty()) {
setFoo(foo);
}
Or is it safer to also check for null on the other side of the OR condition:
if(foo==null || (foo!=null && foo.isEmpty())) {
setFoo(foo);
}
if(foo==null || foo.isEmpty())
is sufficient.
In a Logical OR condition, Java will only evaluate the second part if the first part is false.
No, the first snippet is fine.
In Java (and in many similar languages like C or C++), the logical operators &&
and ||
perform short-circuit evaluation. In the case of ||
, if the left-hand operand is true
, then the right-hand operand won't be evaluated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With