0

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?

3
  • 1
    You have additional parenthesis around the ||. So your claim that | has higher precedence than || is irrelevant as you've placed additional parenthesis in your expression. Commented Feb 4, 2013 at 10:21
  • Parenthesis has the highest precedence, higher than | Commented Feb 4, 2013 at 10:23
  • Ok, you are right. How I did not noticed it?... Commented Feb 4, 2013 at 10:23

2 Answers 2

4

|| 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.

Sign up to request clarification or add additional context in comments.

2 Comments

I totally agree. The misconception derives from not noticing the parenthensis around the first exp
@arjacsoh Ah ok - that makes a difference indeed.
0

| 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.