Using Decrement in Expressions
What you'll learn: How the decrement operator behaves inside expressions and why prefix vs postfix placement matters for the final result.
The Core Idea
Just like increment (++), the decrement operator (--) can be used within expressions, not just as standalone statements. The key difference between prefix and postfix determines when the variable's value is decremented relative to when it's used in the expression.
How Decrement Works in Expressions
Postfix (x--): The current value is used in the expression first, then the variable is decremented afterward.
int count = 5;
int result = count-- * 2; // result gets 5 * 2 = 10, then count becomes 4
System.out.println(result); // 10
System.out.println(count); // 4
Prefix (--x): The variable is decremented first, then the new value is used in the expression.
int count = 5;
int result = --count * 2; // count becomes 4 first, then result gets 4 * 2 = 8
System.out.println(result); // 8
System.out.println(count); // 4
Why This Matters
Think of it like a ticket dispenser. With postfix, you hand out the current ticket number to the expression, then decrement for the next person. With prefix, you decrement first, then hand out the new number.
Both forms always modify the variable, but when that new value becomes visible to the surrounding expression is what changes.
Common Use Cases
Decrement in expressions often appears in countdown scenarios or when processing items in reverse order:
int remaining = 3;
int processed = remaining--; // processed = 3, remaining = 2
Key Takeaway: Postfix x-- uses the old value in the expression then decrements; prefix --x decrements first then uses the new value. Both always modify the variable.