Prachi
Prachi

Reputation: 570

Why do postfix operators in Java get evaluated from right to left?

Suppose we have the following code snippet in Java:

int a = 3;
int b = a++;

The value of a gets assigned to b first and then it gets incremented. b = 3 and a = 4. Then why does the postfix expression get evaluated from right to left? Wouldn't it make more sense for it to be evaluated from left to right?

Upvotes: 1

Views: 729

Answers (3)

biziclop
biziclop

Reputation: 49754

There seems to be some kind of confusion here. Java always evaluates from left to right (or to be more precise, always pretends to do so), as stated in the JLS here:

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

What you're talking about is the direction of associativity, that is if an operand is sandwiched between two operations of the same precedence, which one is the operand bound to. So the ternary operator for example is right-associated because if you've got a?b?c:d:e, you expect it to resolve to a?(b?c:d):e

But the postfix ++, on the same precedence level as the '.' operator is left-to-right associated, which is why foo.bar++ works.

The prefix ++ is indeed right grouping because ++++x should really be `++(++x). Since it's a unary operator and the operand is to the right, it must group to the right.

Upvotes: 0

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

The postfix operators are not evaluated right-to-left; their side-effect happen after the value is determined (roughly speaking - the JLS specifies the order).

Upvotes: 2

nils
nils

Reputation: 1382

Actually: No. This is the expected behaviour. Compare a++ with ++a. If you would do the last one, you would get a=4, b=4.

Upvotes: 0

Related Questions