Win a copy of Design for the Mind this week in the Design forum!

# ++/-- operator

E Weibust
Ranch Hand
Posts: 54
Can someone please tell me why this code prints out a value of 3.
public class Static {
static int x, y;
public static void main( String[] args) {
x--;
System.out.println(x);
myMethod();
System.out.println(x + y + ++x);
} // end main(String[])
public static void myMethod() {
y = (x++ + ++x);
System.out.println(x);
} // myMethod()
} // end Static

Maximiliano Guzenski
Greenhorn
Posts: 2
++x is a pre increment
and x++ is a pos increment
So,
y=(x++ + ++x) it is equal y=(-1 + 1)
and
(x + y + ++x) it is equal (1 + 0 + 2)
[ June 24, 2003: Message edited by: Maximiliano Guzenski ]

Anupam Sinha
Ranch Hand
Posts: 1090
Hi Weibust
Let's number a few locations and see how the code gets executed.

First the 1 is executed which causes x to be -1. Then 2 (a call to myMethod() method) is executed. The method's expression y=(x++ + ++x) evaluates to y = (-1 + (+1)); So y becomes 0 and x is +1. Now 4 is executed which prints out the x value. Then 3 is executed System.out.println(x + y + ++x); which resolves to System.out.println(1 + 0 + 2); which is 3.
[ June 24, 2003: Message edited by: Anupam Sinha ]

E Weibust
Ranch Hand
Posts: 54
I was thinking that if it was a post++ the increment didn't occur until after the expression was evaluated. Looking like:
y = (-1 + (0));
With y getting set to -1 and then x++ occuring and bumping x to 1.

James Chegwidden
Author
Ranch Hand
Posts: 201
Rewrite the code in a simplier way like: Example

For the problem:

so after this step , y = 0, x = 1 which is everyone else said.
I tell my students if the can figure out complex ++/-- in their heads- rewrite it a simplier way to understand it.
[ June 24, 2003: Message edited by: James Chegwidden ]
[ June 24, 2003: Message edited by: James Chegwidden ]
[ June 24, 2003: Message edited by: James Chegwidden ]

Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610

E Weibust
Ranch Hand
Posts: 54
Mr C,
Thanks for clearing that up. Your approach was very useful.
Erik

 It is sorta covered in the JavaRanch Style Guide.