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); } } }
3 Réponses
+ 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.
+ 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.
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?