0

Location of increment and decrement

Does the location of a increment/decrement matter? For example, are these two cases the same? (They produce the same result) 1 . public class Program { public static void main(String[] args) { for(int x = 1; x <=5;) { System.out.println(x); x++; 2. public class Program { public static void main(String[] args) { for(int x = 1; x <=5; x++) { System.out.println(x); } } }

30th May 2018, 2:56 AM
Li Ying Choo
Li Ying Choo - avatar
3 Respostas
+ 6
Does the location matter? Yes. Does it make a difference in your examples? No. However: for (int i = 0; i < 10; i++) { System.out.println(i); } and for (int i = 0; i < 10;) { i++; System.out.println(i); } would yield different values. This is because the for loop syntax is such that the increment happens after the loop body is executed. Placing the increment at the top of the loop body would increment the value of the counter before the rest of the loop contents execute.
30th May 2018, 3:13 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
Li Ying Choo The second would print 1 2 3 4 5 6 7 8 9 10 Since the value of the counter is already incremented before the rest of the loop content runs.
30th May 2018, 2:36 PM
Hatsy Rei
Hatsy Rei - avatar
0
Hmm then according to my understanding of your explanation, for your first example, the printed result would be 0 1 2 3 4 5 6 7 8 9 While for the second one it would be just 1?
30th May 2018, 2:13 PM
Li Ying Choo
Li Ying Choo - avatar