Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Post Fix and preFix Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Post Fix and preFix" Watch "Post Fix and preFix" New topic
Author

Post Fix and preFix

V Jagannadh
Greenhorn

Joined: Dec 20, 2005
Posts: 2
Hi,

int a =10;
int y = a++ - ++a ;
System.out.println(y);

This program is printing -2.
But as per operator precedence PreFix has to be done first and then PostFix.Hence it should have print 0 (Zero).Some body please explain.
Marcelo Ortega
Ranch Hand

Joined: May 31, 2005
Posts: 525

Hi:

int a =10;
int y = a++ - ++a;

//which is:
int y = 10 - 12; //it is 12 because "a" got incremented AFTER the first a++ (which got the value of 11) and then we did ++a (which got the value of 12)

System.out.println(y); //-2

Regards.


SCJP 1.4, SCWCD 1.4, SCBCD 1.3, SCJD, SCEA/OCMJEA

Live life to an interface, not an implementation!
Tilo Hemp
Ranch Hand

Joined: Nov 21, 2005
Posts: 91
evaluation is done from left to right (if consistent with operator precedence).
post-increment (a++) evaluates to a, and only afterward a is incremented by one.
pre-increment (++a) evaluates to a+1

so the expression is equal to:
int tmp = a; // evaluating "a++" to "a"
a += 1; // post-increment of "a++" -> a is now 11
a += 1; // pre-increment of "++a" -> a is now 12
y = tmp - a; // y is -2

or rather to:
y = a - (a = (a += 1) + 1);
which does not contain the additional variable tmp
Ravi Tadysetty
Greenhorn

Joined: Dec 20, 2005
Posts: 2
Tilo

According to operator precedence table, for ++ operator, it is right to left associativity. So, it should evaluate from right to left.

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

Thanks
Ravi
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Post Fix and preFix