Sierra and Bates, in "Sun Certified Programmer & Developer For
Java 2, Exam 310-035; 310-037" pp 215-216, have an example that taught me something I didn't know: | and || don't have the same priority, nor do && and &.
I love the book! Not carping. Just wondering if another
word of explanation might be needed, and curious why Sun did it that way.
The example says: assume doStuff() returns true. Then this code will print true:
int y = 5;
int x = 2;
if ((((x > 3) && (y < 2)) | doStuff()) {
System.out.println("true");
}
No problem. That's what OR means. But then take out of one set of parens:
int y = 5;
int x = 2;
if ((x > 3) && (y < 2) | doStuff()) {
System.out.println("true");
}
This prints nothing, because the effect is as if there were another set of parens:
if ((x > 3) && ((y < 2) | doStuff())) {
The reason: | has higher precedence than &&. I didn't know that! I stared at that a long time. Doesn't AND have higher precedence than OR??? Well, yes, if you're talking about | and &, or about || and &&.
I figured it out, but a real newbie might appreciate another word of explanation.
So my question: why? Got an example where it's useful that | has higher precedence than ||?
Thanks.
Dan McCracken