Alex Rivera | Logout

What is short circuiting and how is it used when programming in Java?

Asked 2012-02-18T21:37:03.370
38

Possible Duplicate:
Does java evaluate remaining conditions after boolean result is known
Why do we usually use || not |, what is the difference?

I missed my class lecture the other day and I was wondering if anyone could give an explanation what short circuiting is and maybe an example of it being used in a simple Java program. Thanks for your help!

Edit
Report

2 Answers

3

Short Circuit: If the first part is true don't bother evaluating the rest of the expression. Same logic applies for false in the case of && which is also short circuiting

answered 2012-02-18T21:40:03.040
0

Short-circuiting the evaluation of an expression means that only a part of the expression needs to be evaluated before finding its value. For example:

a == null || a.size() == 0

If a is null, the a.size() == 0 subexpression won't be evaluated, because the boolean operator || evaluates to true if one of its operands is true.

Similarly, for this expression:

a != null && a.size() > 0

If a is null, then the a.size() > 0 won't be evaluated, because the boolean operator && evaluates to false if one of its operands is false.

In the above examples the boolean operators && and || are said to be short-circuit, given the fact that the second operand might not be evaluated if the value of the first operand is enough to determine the value of the whole expression. For comparison, the & and | operands are the equivalent non-short-circuit boolean operators.

answered 2012-02-18T21:41:50.680

Your Answer