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
++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: 1088
posted
0
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
posted
0
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
posted
0
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 ]
Mr. C<br /> <br />Author and Instructor<br />My book:<br /><a href="http://www.aw-bc.com/catalog/academic/product/0,1144,1576761614,00.html" target="_blank" rel="nofollow">http://www.aw-bc.com/catalog/academic/product/0,1144,1576761614,00.html</a>