AP Computer Science Java: Lesson 2.5
Conditional Statements - Short-Circuiting


Lesson 2.5 - Short-Circuiting

Purpose: To learn how the AND and OR operators short-circuit

Smooth Operators
  In the last lesson that we discussed how the logical operators AND and OR work. Recall that an AND will engage if both of its conditions are true and an OR wll engage if at least one of its conditions are true. Because of these facts, it is possible for the computer to "skip out" of an AND or OR if their rules for engagement are violated by the first condition. This is called short-circuiting.

Short-circuiting may sound like a bad thing (it is in terms of electricity) but in computer science, it means that the computer is saving time by not evaluating conditions that it doesn't need to consider. Let's look at an example involving the AND operator. Consider the following code:

   if(x==1 && y>5)
   {
      list of statements...
   }

Suppose that x is not 1. That means the condition x==1 is false. Since AND requires both conditions to be true to engage the list of statements, the result of the condition y>5 is irrelevant. In other words, it doesn't matter whether y>5 is true or false because the first condition is already false, making it impossible for both to be true. So in general, when the first condition of an AND is found to be false, the computer short-circuits the AND by skipping the second condition.

What is the point? Consider that in a large program with thousands of conditions to be evaluated, this results in saved time. Programmers seek to make programs that not only function correctly, but also as efficiently as possible. The short-circuit capability of Java helps toward that goal.

Short-Circuit with OR  The OR operator also has the capability to short-circuit. Recall that an OR will engage when either one of its conditions is true. So if the first condition is true, the value of the second condition is irrelevant. See the example code below:

   if(x==1 || y>5)
   {
      list of statements...
   }

In the example, if x is indeed 1, the condition x==1 is true. Since OR requires only one of the conditions to be true to engage the list of statements, the result of the condition y>5 is irrelevant. In other words, it doesn't matter whether y>5 is true or false because the first condition is already true, making the overall result of the OR true. So in general, when the first condition of an OR is found to be true, the computer short-circuits the OR by skipping the second condition.


In closing
, short-circuiting is in place in Java to speed up the evaluation of logical conditions. The computer does this on its own, so the programmer doesn't need to do anything to make it happen. Just remember the following:

   1. The AND operator will short-circuit when the first condition is FALSE
   2. The OR operator will short-circuit when the first condition is TRUE


© DanShuster.com