Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# Post increment and Pre Increment Precedence

Gaurav Chauhan
Greenhorn
Posts: 27
I am studying for SCJP and using Khalid Mughal as my first main book. I was working on operators and i got into the following problem :

According to KHALID MUGHAL book chapter no.3 page no 82 the precedence table states that POSTFIX OPERATOR have highest precedence followed by unary prefix.

If i work according to this rule the

i=10
a = i++ + ++i + i--;
a = 10 /*i became 11 now */ + ++i + 11 // now i became 10
a = 10 + 11 +11 = 32

output is 32. But actual output is 34.

In COMPLETE REFERNCE the precedence of both PREFIX AND POSTFIX is same.

Which one shall i follow ? and Kindly correct me if i am wrong in above problem.
[ August 05, 2008: Message edited by: Gaurav Chauhan ]

Gaurav Chauhan
Greenhorn
Posts: 27
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html

http://www.uni-bonn.de/~manfear/javaoperators.php

http://www.cs.uwf.edu/~eelsheik/cop2253/resources/op_precedence.html

The difference in precedence in above mentioned links

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24211
35
There are three terms in the sum. The value of the first term is 10, the value of the postincrement operator. "i" is then incremented, so its value is 11. Then the value of the second term is 12; that's the value of the preincrement operator (11 + 1), and i is now 12. The sum after two terms is 22. Then you add i--, which is also 12: again, the postdecrement operator returns the unmodified value. 10 + 12 + 12 is 34.

[ Gaaah! Fixed typo ]
[ August 05, 2008: Message edited by: Ernest Friedman-Hill ]

Prasanna Venkatesh
Greenhorn
Posts: 11
Ya interesting problem , It has to be 32 , guess this may be a bug in JVM implementation.

Larry Frissell
Ranch Hand
Posts: 82
2
Ernest Friedman-Hill said "the postdecrement operator returns the unmodified value. 10 + 12 + 12 is 32. "

I assume that 10+12+12 is still 34.
Larry

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24211
35
Sorry. Fixed my typo

eshu khare
Ranch Hand
Posts: 44
Try Head First Java for tutorials,complete refrence is ok but khalid mugal is quite brief as per for a beginner.Ernest Friedman-Hill's reply is solution to your problem.

Gaurav Chauhan
Greenhorn
Posts: 27
This concept really solves the problem and gets me the exact result.

But if we look at the precedences on SUN WEBSITE link given above. That says that postfix is at the top of list followed by unary prefix. Is this wrong there ?

One more problem try this folks:

int x =7, y =10;

System.out.println( x++ - y++ + ++x + ++y) ;

x++ - y++ + ++x + ++y
7 - 10 + 9 + 12
18
It works according to the rule given by the member.