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
Let's take your example expression:
boolExp1 || boolExp2 && boolExp3 || boolExp4
Now we believe that acts as:
boolExp1 || (boolExp2 && boolExp3) || boolExp4
right?
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:
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.