checking object reference for null in if statement along with other object's methods [duplicate]

StackOverflow https://stackoverflow.com/questions/23619825

문제

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.

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top