pf_miles pf_miles - 1 year ago 70
Java Question

How to PROVE the precedence of '&&' and '||' by CODING in java?

I knew from somewhere that logical and: '&&' has a higher precedence than logical or: '||' in java.And while programming I rarely make mistakes on them. But till now I didn't find any clue about how this precedence really act? What would happen if I didn't know about the precedence of the two and what mistake would I make?
I tried to write some code to PROVE the precedence of '&&' and '||' but failed, for example:

boolExp1 || boolExp2 && boolExp3 || boolExp4

the code above would produce same results no matter the precedence of '&&' and '||', that is ,
'false || false && true || false' results false no matter what the precedence are.

So, in other words, I want a method or function, that could PROVE the precedence of '&&' and '||', it should produce different results depends on the precedence of '&&' and '||'...
How could this function being made?Is it possible?
I guess it maybe a tough question or a dramatically simple one...may be it's not a java problem but something math...
All in all, somebody help?

Answer Source

Let's take your example expression:

boolExp1 || boolExp2 && boolExp3 || boolExp4

Now we believe that acts as:

boolExp1 || (boolExp2 && boolExp3) || boolExp4


So let's suppose the opposite is true, and it's actually

(boolExp1 || boolExp2) && (boolExp3 || boolExp4)

What values of boolExp1 etc would give us different results?

Well, let's take:

boolExp1 = true
boolExp2 = false
boolExp3 = false
boolExp4 = false

Under the "&& has higher precedence" rules, the result would be true. Under the "|| has higher precedence rules", the result would be false. A quick test shows that the expression evaluates to true, however.

Of course, this doesn't actually prove that && has higher precedence than || - merely that || doesn't have higher precedence than &&. We could consider whether they have equal precedence - and test that with other expressions in a similar way... find a sample expression and values which would give different results under different precedence rules, and test them.

Ultimately though, I prefer:

  • To trust the spec unless I have specific doubts
  • To use parentheses to make my intentions clear

I wouldn't use the first expression "as is" in the first place... because unless you actually know the precedence rules (and I suspect many Java devs don't - I couldn't swear that I'd have got && and || right) you're in the dark. Better to make it explicit and clear where there's any doubt.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download