Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Precedense and Associativity of Operators

Amol Katyare
Greenhorn
Posts: 5
Hello All,

Though it seems to be very basic question, but I am unable to find the correct reason. Can you please explain why the output of the following code is X=2 Y=2? I was expecting it to be X=2, Y=3.

public static void main(String[] args)
{
int x = 1, y = 0;
y = x + y + (x++);
System.out.println("X= " + x +" Y= " + y );
}

I think compiler is evaluating it as y = 1 + 0 + 1;
But per the rules of precedense x++ should be evaluated first. (Though the brackets are redundant in this case as postfix unary operators have more precedense than the binay + operator). Hence, per my guess work it should have been evaluated as y = 2 + 0 + 1.

marc weber
Sheriff
Posts: 11343
Originally posted by Amol Katyare:
... I think compiler is evaluating it as y = 1 + 0 + 1 ...

That's correct.

Per the Java Language Specification section 15.7...
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

And section 15.7.2...
The Java programming language also guarantees that every operand of an operator ... appears to be fully evaluated before any part of the operation itself is performed.

Garrett Rowe
Ranch Hand
Posts: 1296
An alternative explanation from the Sun tutorial on Arithmetic Operators
Two shortcut arithmetic operators are ++, which increments its operand by 1, and --, which decrements its operand by 1. Either ++ or -- can appear before (prefix) or after (postfix) its operand. The prefix version, ++op/--op, evaluates to the value of the operand after the increment/decrement operation. The postfix version, op++/op--, evaluates to the value of the operand before the increment/decrement operation.