Question

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.

Was it helpful?

Solution

&& 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top