Java Increment & Decrement
In this page:
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: