The moose likes Beginning Java and the fly likes Precedense and Associativity of Operators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Precedense and Associativity of Operators" Watch "Precedense and Associativity of Operators" New topic

Precedense and Associativity of Operators

Amol Katyare

Joined: Mar 28, 2006
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.

Can anybody please explain this?
marc weber

Joined: Aug 31, 2004
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.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
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.

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
I agree. Here's the link:
subject: Precedense and Associativity of Operators
It's not a secret anymore!