This week's book giveaway is in the Android forum.We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!See this thread for details.
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of Head First Android this week in the Android forum!

# Short circuit operators

deva raj
Greenhorn

Joined: May 28, 2004
Posts: 6

Can anyone explain how does this work? Please let me know if there any good weblinks to get information about short circuit operators?

Thanks
Narayan

Edited by Corey McGlone: Added CODE Tags
[ May 28, 2004: Message edited by: Corey McGlone ]
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
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.

SCJP Tipline, etc.
deva raj
Greenhorn

Joined: May 28, 2004
Posts: 6
Great...Great.. I understood the concepts
Thanks alot

I agree. Here's the link: http://aspose.com/file-tools

subject: Short circuit operators