Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# short / long circuit operators functionally different?!

Tilo Hemp
Ranch Hand
Posts: 91
Hi all!

Up to this morning, I thought that the logical operators || and | (or && and &, respectively) were functionally the same, as long as they do not change the state of any variables.

But then I came to page 321 of the excellent K&B book, which inspired me to write the code:

which prints

true
false

Pleas explain!

I have to apologize if this has been asked before, I tried the search function but there were too many / too few answers (depending on for what I searched).

Regards

Barry Gaunt
Ranch Hand
Posts: 7729
The & and | operators have higher precedence than && and ||.
If you bracket your expressions according to precedence you will see why you get the results you do.

Craig Tyler
Ranch Hand
Posts: 52
This is as much of a precedence issue as it is the difference between short and "long" circuit operators. The short-circuit operators have a lower precedence, so the two expressions end up like so:

In the first expression, as the & operator is of higher precedence than |, the two falses get grouped together, but the entire expression results in a true value since "false | true" is true.

The second expression gives higher precedence to the | operator, so "false | true" get grouped together. Here, however, the short-circuit operator stops at the first false since it wouldn't matter what the second grouping would result in.

Hope this helps.

Tilo Hemp
Ranch Hand
Posts: 91
ah, I see... so it is a precedence issue. Will such things be in the Java 5 exam? Because in the K&B book, it says the operator precedence is not on the exam except for +- vs. */ (as far as I understood - so I didn't have a deeper look onto it). And now there comes along this example based on operator precedence... does that mean its important after all?

Anyway, I suppose it would not be much effort learning it by heart...
[ February 22, 2006: Message edited by: Tilo Hemp ]

Edisandro Bessa
Ranch Hand
Posts: 584
Hi Tilo,

Just in addition to Barry's post, the precedence for logical operator is :

^ 1st --> & 2nd --> | 3rd --> && 4th --> || 5th.

If you want to take a brief look at thread I started in the past here is the link:

http://www.coderanch.com/t/252813/java-programmer-SCJP/certification/Logical-Operators-Precedence

Tilo Hemp
Ranch Hand
Posts: 91
Hi,

thanks a lot everybody! Although I am still not sure how much I will need it, it's good to have this information!

Greetings
Tilo
[ February 22, 2006: Message edited by: Tilo Hemp ]

levani dvalishvili
Ranch Hand
Posts: 99
in practice I find short sircuit operations very convinient, when you have to do null checking, something like this

or

if you do these with & or with | operators and the obj is null code will throw nullponterexception and will breake right away.
[ February 22, 2006: Message edited by: levani dvalishvili ]