Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to check null on both sides of an OR condition?

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

}
like image 580
Vladimir Avatar asked Dec 03 '22 01:12

Vladimir


2 Answers

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.

like image 199
jbx Avatar answered Jan 25 '23 23:01

jbx


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.

like image 33
Oliver Charlesworth Avatar answered Jan 25 '23 23:01

Oliver Charlesworth