Learn how to use the pre-increment (++i), post-increment (i++), pre-decrement (--i), and post-decrement (i--) operators in Java.
Java · beginner · 15 min · 18 steps · free
public class IncrementDecrementDemo {
public static void main(String[] args) {
// Post-increment (a++)
int a = 5;
System.out.println("Initial a: " + a);
int b = a++; // b gets the original value of a, then a is incremented
System.out.println("After a++:");
System.out.println("a is " + a);
System.out.println("b is " + b);
// Pre-increment (++c)
int c = 5;
System.out.println("Initial c: " + c);
int d = ++c; // c is incremented first, then d gets the new value of c
System.out.println("After ++c:");
System.out.println("c is " + c);
System.out.println("d is " + d);
// Post-decrement (x--)
int x = 10;
System.out.println("Initial x: " + x);
int y = x--; // y gets the original value of x, then x is decremented
System.out.println("After x--:");
System.out.println("x is " + x);
System.out.println("y is " + y);
// Pre-decrement (--z)
// Same logic decreases the value and then assign the decreased value
// int z = 10;
// System.out.println("Initial z: " + z);
// int w = --z; // z is decremented first, then w gets the new value of z
// System.out.println("After --z:");
// System.out.println("z is " + z);
// System.out.println("w is " + w);
// result will be ->
// z is 9
// w is 9
}
}a and initialize it with the value 5.a is printed to the console.a++) is used. First, the original value of a (5) is assigned to b.a is incremented. Its value changes from 5 to 6.a (which is 6) is printed.b (which is 5) is printed. Note how it holds the value of a before the increment.c to 5.c to 5.++c) is used. First, c is incremented. Its value changes from 5 to 6.c (6) is assigned to d.c (now 6) is printed.d is also 6. Note how both c and d have the same value after the operation.x to 10.x--), the original value of x (10) is assigned to y. Then x becomes 9.x--), the original value of x (10) is assigned to y. Then x becomes 9.x--), the original value of x (10) is assigned to y. Then x becomes 9.x--), the original value of x (10) is assigned to y. Then x becomes 9.x--), the original value of x (10) is assigned to y. Then x becomes 9.i++ and ++i are always interchangeable. They only behave the same when used as a standalone statement (e.g., i++;).i++;) rather than embedded in complex expressions.int x = i++ + ++i;) as it leads to confusing and hard-to-read code.← Assignment Operators · Bitwise Operators →