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) 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) 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.
1. The AND operator will short-circuit when the first condition is FALSE
|
|||||||||||
© DanShuster.com