Home   Cover Cover Cover Cover
 

Short Circuit Evaluation

Question: Why is short-circuit evaluation important in the following loop header?

    while (p != null && p.name != "John") {...}

Answer: Short circuit evaluation is important in this example, because p.name may only be evaluated if p != null. If the first term of the condition (i.e. p != null) is false the second term (i.e. p.name != "John") is not evaluated any more, which avoids a null pointer exception.