arjacsoh
arjacsoh

Reputation: 9232

Operators precedence in Java gets confusing

I set a similar question a few weeks ago but I cannot still dissolve the ambiguity and the confusion on java operators precedence. This time I have this fragment of code:

int mask = 0;
int count = 0;
if( ((5<7) || (++count < 10)) | mask++ < 10 )   
    mask = mask + 1;
System.out.println(mask + " " + count);

The result is (unexpectedly to me): 2 0.

Moreover, the compiler provides a warning underlining only the expression (++count<10): dead code.

I reckon however the execution of the code though as either one of the following ways:

1) | has a higher precedence than ||, hence it is considered as there were parenthesis around the expression ( (++count<10) | mask++ <10). This way the compiler should have executed the both parts and count should have been set to 1 (++count<10).

2) If the compiler looks first the (5<7) and after evaluating it to false skips the entire second expression, then mask should not have been increased and we would wait the value 1 in the output.

What have I misunderstood and cannot explain the behavior of the compiler, as well as the output?

Upvotes: 0

Views: 178

Answers (2)

user207421
user207421

Reputation: 310874

| has a higher precedence than ||, hence it is considered as there were parenthesis around the expression ((++count<10) | mask++ <10).

There is no such expression in your code. Look again. The entire expression is ( ((5<7) || (++count < 10)) | mask++ < 10 ). The || associates the constant test 5<7 with ++count < 10, which can never be executed because the constant test is always false, and the | associates all that with mask++ < 10.

There is in fact no operator precedence problem here at all, just your own misunderstanding of where you have put your parentheses.

Upvotes: 0

assylias
assylias

Reputation: 328598

|| is an OR operator that only evaluates its right hand side expression if the left hand side expression is false. In your case, 5 < 7 is true and ++count < 10 is not evaluated.

On the other hand, | always evaluates both expressions: even if ((5<7) || (++count < 10)) is true, mask++ < 10 will be evaluated.

Upvotes: 4

Related Questions