Post-increment assignment first assigns the value and then increments it, whereas, Pre-increment assignment first increments the value and then assigns the value.
Note the difference in the values of method variables postIncrement and preIncrement
Also note that in For loop, irrespective of post-increment or pre-increment of method variable x, the output of the two codes remain same
public class PreAndPostIncrementTest {
public static void main(String... args) {
int x;
for (x = 1; x < 10; ++x)
System.out.println(x);
int postIncrement = x++; // should be 10
int preIncrement = ++x; // should be 12
System.out.println("postIncrement is " + postIncrement);
System.out.println("preIncrement is " + preIncrement);
}
}
OR
public class PreAndPostIncrementTest {
public static void main(String... args) {
int x;
// Note: Here x++ is used instead of ++x in above example
for (x = 1; x < 10; x++)
System.out.println(x);
int postIncrement = x++; // should be 10
int preIncrement = ++x; // should be 12
System.out.println("postIncrement is " + postIncrement);
System.out.println("preIncrement is " + preIncrement);
}
}