The || operator is like | (�15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false.
For |, the result value is false if both operand values are false; otherwise, the result is true.
Originally posted by Kareem Qureshi:
Given the following definition:
String s = null;
Which code fragment will cause an exception of type NullPointerException to be thrown.
1.if ((s != null) & (s.length()>0))
2.if ((s != null) && (s.length()>0))
3.if ((s != null) | (s.length()>0))
4.if ((s != null) || (s.length()>0))
5.None of the above.
Answer given are 1,2,3,4
Explaination for answers are given below.
For the following, LHS is left-hand side, RHS = right hand side.
Answer 1 must be fully evaluated. The LHS is true and so the RHS needs to be evaluated to ensure the entire expression is true. This is an AND operation, and if the LHS is true, then the RHS must be evaluated for the expression to be true.
Answer 2 is the same as above. Both sides need to be evaluated for an AND expression to be true (if the LHS is true, that is)..
Answer 3 must be fully evaluated because an OR expression is only true if one or the other is true, but not both. Therefore, since the LHS is true, the RHS must be evaluated.
Answer 4 is similar to answer 3 above.