This week's book giveaway is in the OCAJP 8 forum.We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!See this thread for details.
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!

# ++/-- operator

E Weibust
Ranch Hand

Joined: Jun 13, 2003
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

---<br />Erik Weibust<br /><a href="http://erik.weibust.net" target="_blank" rel="nofollow">http://erik.weibust.net</a>
Maximiliano Guzenski
Greenhorn

Joined: Jun 24, 2003
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

Joined: Apr 13, 2003
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

Joined: Jun 13, 2003
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

Joined: Oct 06, 2002
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 ]

Author and Instructor, my book
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610

SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
E Weibust
Ranch Hand

Joined: Jun 13, 2003
Posts: 54
Mr C,
Thanks for clearing that up. Your approach was very useful.
Erik

I agree. Here's the link: http://aspose.com/file-tools

subject: ++/-- operator