Increment and Decrement

Prefix and Postfix

++ adds 1 and -- subtracts 1. The position matters when the result is used in the same expression.

  • Prefix ++x: increase first, then use the new value.
  • Postfix x++: use the current value first, then increase.

Example

public class Main {
    public static void main(String[] args) {
        int x = 5;
        int a = x++;    // a gets 5, then x becomes 6
        System.out.println("a = " + a + ", x = " + x);

        int y = 5;
        int b = ++y;    // y becomes 6, then b gets 6
        System.out.println("b = " + b + ", y = " + y);

        int stock = 3;
        stock--;
        System.out.println("stock = " + stock);
    }
}

Output

a = 5, x = 6
b = 6, y = 6
stock = 2

Tip

Tip: Use ++ and -- as standalone statements (count++;). Avoid tricky lines like x = x++ + ++x;; they are popular in MCQ tests but confusing in real code.

Exercise: What is printed? int i = 10; int j = i++ + ++i; System.out.println(i + " " + j);

Show answer
12 22
i++ gives 10 (i becomes 11), ++i makes i 12 and gives 12, so j = 10 + 12 = 22.