# Short circuit operators

deva raj

Greenhorn

Posts: 6

Corey McGlone

Ranch Hand

Posts: 3271

posted 12 years ago

Short Circuit operators take advantage of the rules of logic to streamline code. For example, if you have the expression:

false && someBoolean

You can tell simply by looking at the first part that this will always evaluate to false. The literal false "ANDed" with anything is always going to give false. Likewise, this statement:

true || someBoolean

will always result in a true result. It doesn't matter what someBoolean is, the literal true "ORd" with anything will result in a true result.

In your program, the JVM is taking advatange of that. Basically, it will begin evaluating operands from left to right until it can determine the final outcome and, once it does, it moves on without bothering to evaluate the remaining operands.

So, what does that mean in your example? Well, look at this line:

b = (t || ((i++) == 0));

The JVM starts with the left-most operand and evaluates it. It finds that t is true. Well, now we're going to OR t with some other operand. But hold on a second! We don't need to. We know that t is true and we know that true "ORd" with anything will result in a true result. Therefore, the JVM can skip the rest of that line and move to this line:

b = (f || ((i+=2) > 0));

In this case, f is false so we must go on to evaluate the second operand. That second operand has the side-effect of adding 2 to i before evaluating to true. That's why, when you execute this, you get a value of 2 printed.

false && someBoolean

You can tell simply by looking at the first part that this will always evaluate to false. The literal false "ANDed" with anything is always going to give false. Likewise, this statement:

true || someBoolean

will always result in a true result. It doesn't matter what someBoolean is, the literal true "ORd" with anything will result in a true result.

In your program, the JVM is taking advatange of that. Basically, it will begin evaluating operands from left to right until it can determine the final outcome and, once it does, it moves on without bothering to evaluate the remaining operands.

So, what does that mean in your example? Well, look at this line:

b = (t || ((i++) == 0));

The JVM starts with the left-most operand and evaluates it. It finds that t is true. Well, now we're going to OR t with some other operand. But hold on a second! We don't need to. We know that t is true and we know that true "ORd" with anything will result in a true result. Therefore, the JVM can skip the rest of that line and move to this line:

b = (f || ((i+=2) > 0));

In this case, f is false so we must go on to evaluate the second operand. That second operand has the side-effect of adding 2 to i before evaluating to true. That's why, when you execute this, you get a value of 2 printed.

deva raj

Greenhorn

Posts: 6

It is sorta covered in the JavaRanch Style Guide. |