0

I am not convinced why below statement is valid and does not throw exception.

 ArrayList <String> some_list = null;

 if (some_list != null && some_list.size() > 0) {
   // do something...not important if I get here or not.
 }

some_list is null, and first check in if() is valid, but what about getting size on a null reference? isn't this illegal ?

or does it work this way:

 if (codition1 && condition2) {
 }

only if condition1 is true check condition2 ?

since I am not convinced , although I confirmed by writing test code. I always do like below:

if (some_list != null) {
  if (some_list.size() > 0) {
  }
} 

Please help me understand the logical && and null point checking in if statement. Thank you.

David Prun
  • 8,203
  • 16
  • 60
  • 86
  • 1
    `&&` is short circuiting. If the left operand is evaluated to false, you already know that the condition cannot be true, so it won't be evaluated. `if (some_list != null && some_list.size() > 0)` is the way to go. – Alexis C. May 12 '14 at 22:15
  • Additionally: if you do want to always evaluate both expressions , use the `|` and `&` operators. – Jeroen Vannevel May 12 '14 at 22:19

1 Answers1

3

&& is "short circuiting". The expression on the right is never executed if the expression on the left evaluates to false.

The same is true for ||, which never executes the expression on the right if the expression on the left is true.

& and | are normally used for bit operations on integers, but can also be used on booleans. These are not short-circuiting. If you had done

if ((some_list != null) & (some_list.size() > 0)) { 

then it would have failed in exactly the way you're asking about.

that other guy
  • 116,971
  • 11
  • 170
  • 194