3

I have a simple Java expression depicted below. Based on Operator Precedence table, I expect that this expression would return division by zero exception (since post-fix increment operator has highest priority) and expect that resulting expression would look like:

2 + 2 + 5 / 0 

But result is 7, why ? (By little bit of experimentation I found that all operators are assigned value of 1 for some reason, but this does not make sense to me in case priority table is correct)

int intCountOperator = 0; unaryOperand = ++intCountOperator + intCountOperator + 5 / intCountOperator++; System.out.println(unaryOperand); // Prints 7 
1
  • It's because of left-to-right evaluation order, which is orthogonal to operator precedence. Commented Dec 21, 2015 at 13:50

3 Answers 3

2

The operator precedence does not control the evaluation order. It controls only how the expression is to be read. For example, since multiplication has a higher precedence than addition, x + y * z is read as x + (y * z), not (x + y) * z. However, it does not change that first x is evaluated, then y and finally z.

Giving a good example with ++ and -- is more difficult, because there is usually only one reading which makes sense. However, you might notice that y - x++ compiles without error (if x and y are numerical variables). If ++ would have had a lower precedence than - it would be evaluated as (x - y)++ which would not compile.

Because of operator precedence, your expression is evaluated as:

(++intCountOperator) + (intCountOperator + (5 / (intCountOperator++))); 

but the evaluation order is not changed by it.

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

Comments

2

The expression is evaluated from left to right :

unaryOperand = ++intCountOperator + intCountOperator + 5 / intCountOperator++; 1 + 1 + 5 / 1 = 7 

Note that the operators are evaluated in the order you expect, i.e. 1 + 1 + (5/1) = 1 + 1 + 5 = 7, but the operands of all those expressions are evaluated from left to right.

Comments

1

The order of evaluation is from left to right and not right to left. So the result 7 which you are getting is correct.

unaryOperand = ++intCountOperator + intCountOperator + 5 / intCountOperator++; 

is actually

unaryOperand = 1 + 1 + 5 / 1; = 7 

3 Comments

Thanks, however I'm a bit surprised then, expected that highest priority operators are evaluated first. Like when I evaluate 5 + 6 / 3 it first evaluates division, then addition (because of priority)
Java always evaluates operands left-to-right. Operator precedence tells you the order in which those operands are subsequently combined.
In te latter it first evaluates 5/1 then thé additions So wbat is the problème. Thé only thing thats changes is thé évaluation of PREfixe operator which has a higher priorité in ghe table anyways.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.