public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i++); // I am loosing it here..if i=0 ; j = i++; that I know that j will be zero, but 4 that I am loosing it
}
}
}
vuthlarhi donald wrote:// I am loosing it here..if i=0 ; j = i++; that I know that j will be zero, but 4 that I am loosing it
where did j come from?
Thanks
Preparing for SCJP 6
vuthlarhi donald
Ranch Hand
Joined: Jul 31, 2006
Posts: 76
posted
0
Just wanted to ilustarte that I know how the post increament works, but I don't get it when we return back to the loop..so you can ignore the comments..
Never ascribe to malice that which can be adequately explained by stupidity.
vuthlarhi donald
Ranch Hand
Joined: Jul 31, 2006
Posts: 76
posted
0
the question is I don't understand the output
0,2,4
Eduardo Bueno
Ranch Hand
Joined: Jun 04, 2009
Posts: 151
posted
0
You're always in the same scope. When you use i++ in the println(), it prints 0 and after that i becomes 1, returning to the beggining of the loop with this value. The for statement will then increment i, which becomes 2, prints 2, and so on.
This message was edited 1 time. Last update was at by Eduardo Bueno
Sridhar Gudipalli
Ranch Hand
Joined: Nov 02, 2005
Posts: 120
posted
0
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i++);
}
}
}
iteration 1:
--------------
i value is 0; (0<5 test is pass)
prints 0 then increments i value (i is now 1) //output is: 0
i is incremented in for loop (i is now 2)
iteration 2:
------------
i value is 2; (2<5 test is pass)
prints 2 then increments i value (i is now 3)//output is: 0 2
i is incremented in for loop (i is now 4)
iteration 3:
------------
i value is 4; (4<5 test is pass)
prints 4 then increments i value (i is now 5) //output is: 0 2 4
i is incremented in for loop (i is now 6)
iteration 4:
------------
i value is 6; (6<5 test is fail)