← Back to Core Java Course | Chapter 3: Operators | Lesson 7 of 9

Java Increment & Decrement

Post-Increment Operator

In int y = x++;, y receives x's value from before the increment, and only afterward does x's own stored value go up by one -- the post in post-increment refers to when the increase takes effect relative to the read.

Example: Post-Increment Operator

java
public class Main {
	public static void main(String[] args) {
		int x = 5;
		int y = x++; // y gets 5 (old value), x becomes 6 afterward
		System.out.println(y + " " + x);
	}
}

Pre-Increment Operator

In int y = ++x;, x is incremented first, and that already-updated value is what gets assigned to y -- so pre-increment and post-increment produce the same end state for x, but different values for y.

Example: Pre-Increment Operator

java
public class Main {
	public static void main(String[] args) {
		int x = 5;
		int y = ++x; // x becomes 6 first, y gets the already-updated 6
		System.out.println(y + " " + x);
	}
}

Post-Decrement Operator

Post-decrement (x--) mirrors post-increment: the expression evaluates to x's current value, and the actual decrease by one happens immediately after that value has been used.

Example: Post-Decrement Operator

java
public class Main {
	public static void main(String[] args) {
		int x = 5;
		int y = x--; // y gets 5, then x decreases to 4 afterward
		System.out.println(y + " " + x);
	}
}

Pre-Decrement Operator

Pre-decrement (--x) subtracts one from x first, then the already-lowered value is what the surrounding expression sees and uses.

Example: Pre-Decrement Operator

java
public class Main {
	public static void main(String[] args) {
		int x = 5;
		int y = --x; // x drops to 4 first, y gets that already-lowered value
		System.out.println(y + " " + x);
	}
}

Mixed Expressions

Mixing several ++ and -- operators inside one complex expression (like a[i++] = b[--j]) works, but it also makes evaluation order much harder to trace at a glance -- most style guides recommend splitting these onto separate lines.

Example: Mixed Expressions

java
public class Main {
	public static void main(String[] args) {
		int[] a = {10, 20, 30};
		int i = 0, j = 2;
		a[i++] = a[--j]; // hard to trace at a glance - most style guides avoid this
		System.out.println(a[0] + " " + i + " " + j);
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.