4

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);

}
Vladimir
  • 41
  • 2

5 Answers5

12

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.

jbx
  • 21,365
  • 18
  • 90
  • 144
  • 2
    In a *logical* OR expression. In *bitwise* OR, they are both evaluated. – Mark Peters Sep 04 '11 at 18:30
  • On a side note if u r going to have several such checks it is always a good idea to extract this into a method.. Something on the lines of StringUtils.. – Scorpion Sep 04 '11 at 18:32
4

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.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
2

Welcome to Stack Overflow

Operators like ||, && in Java are short-circuit operator, the second part of expression will only be checked when first part are not enough to determine the value

so, if(foo==null || foo.isEmpty()) is sufficient.

Rangi Lin
  • 9,303
  • 6
  • 45
  • 71
0
if (foo == null || foo.isEmpty()) setFoo(foo);

Works fine. In this case, if foo is null, setFoo(foo) will be called. If foo isn't null, and foo is empty, setFoo(foo) will also be called.

fireshadow52
  • 6,298
  • 2
  • 30
  • 46
0

I find it more elegant to use StringUtils.isBlank(foo) (from apache commons-lang), so you don't need the || at all.

Arnout Engelen
  • 6,709
  • 1
  • 25
  • 36