Java Increment & Decrement Operators
Increment & Decrement Operators
Increment (++) and decrement (--) operators are special shorthand operators in Java that increase or decrease a variable's value by 1. Understanding the difference between pre and post forms is crucial for writing correct code.
Goal: Master increment and decrement operators, understand the critical difference between prefix and postfix forms, and avoid common mistakes.
Key Insight: The position of ++ or -- matters! ++x increments THEN returns the value. x++ returns the value THEN increments. This subtle difference causes many bugs in real code.
What are Increment/Decrement Operators?
Increment (++): Increases value by 1
Decrement (--): Decreases value by 1
int x = 5;
x++; // x becomes 6
x++; // x becomes 7
x--; // x becomes 6Equivalent Operations:
// These are all equivalent:
x++; // Increment
x = x + 1; // Add 1
x += 1; // Add 1 shorthandTwo Forms: Prefix vs Postfix
Prefix Form (++x or --x)
Prefix: Increment/decrement FIRST, THEN use the value.
int x = 5;
int y = ++x; // x becomes 6 first, then y gets 6
System.out.println("x = " + x); // Output: x = 6
System.out.println("y = " + y); // Output: y = 6Step by Step:
- ›Increment
xfrom 5 to 6 - ›Assign the new value (6) to
y
Postfix Form (x++ or x--)
Postfix: Use the value FIRST, THEN increment/decrement.
int x = 5;
int y = x++; // y gets 5 first, then x becomes 6
System.out.println("x = " + x); // Output: x = 6
System.out.println("y = " + y); // Output: y = 5Step by Step:
- ›Assign current value (5) to
y - ›Increment
xfrom 5 to 6
Increment Operator (++)
Pre-increment (++x)
public class PreIncrementDemo {
public static void main(String[] args) {
int x = 10;
System.out.println("Initial x: " + x); // Output: 10
int y = ++x; // Increment x first, then assign to y
System.out.println("After ++x:");
System.out.println("x = " + x); // Output: 11
System.out.println("y = " + y); // Output: 11
}
}Execution Order:
- ›
xis incremented to 11 - ›The new value (11) is assigned to
y
Post-increment (x++)
public class PostIncrementDemo {
public static void main(String[] args) {
int x = 10;
System.out.println("Initial x: " + x); // Output: 10
int y = x++; // Assign to y first, then increment x
System.out.println("After x++:");
System.out.println("x = " + x); // Output: 11
System.out.println("y = " + y); // Output: 10
}
}Execution Order:
- ›The current value (10) is assigned to
y - ›Then
xis incremented to 11
Side-by-Side Comparison
public class IncrementComparison {
public static void main(String[] args) {
// Pre-increment
int a = 5;
int b = ++a;
System.out.println("Pre-increment:");
System.out.println("a = " + a + ", b = " + b); // a = 6, b = 6
// Post-increment
int x = 5;
int y = x++;
System.out.println("\nPost-increment:");
System.out.println("x = " + x + ", y = " + y); // x = 6, y = 5
}
}Decrement Operator (--)
Pre-decrement (--x)
public class PreDecrementDemo {
public static void main(String[] args) {
int x = 10;
System.out.println("Initial x: " + x); // Output: 10
int y = --x; // Decrement x first, then assign to y
System.out.println("After --x:");
System.out.println("x = " + x); // Output: 9
System.out.println("y = " + y); // Output: 9
}
}Post-decrement (x--)
public class PostDecrementDemo {
public static void main(String[] args) {
int x = 10;
System.out.println("Initial x: " + x); // Output: 10
int y = x--; // Assign to y first, then decrement x
System.out.println("After x--:");
System.out.println("x = " + x); // Output: 9
System.out.println("y = " + y); // Output: 10
}
}Decrement Comparison
public class DecrementComparison {
public static void main(String[] args) {
// Pre-decrement
int a = 10;
int b = --a;
System.out.println("Pre-decrement:");
System.out.println("a = " + a + ", b = " + b); // a = 9, b = 9
// Post-decrement
int x = 10;
int y = x--;
System.out.println("\nPost-decrement:");
System.out.println("x = " + x + ", y = " + y); // x = 9, y = 10
}
}In Expressions
Prefix in Expressions
public class PrefixExpressions {
public static void main(String[] args) {
int x = 5;
int result = ++x * 2; // x becomes 6, then 6 * 2 = 12
System.out.println("x = " + x); // Output: x = 6
System.out.println("result = " + result); // Output: result = 12
}
}Evaluation:
- ›
++xincrements x to 6 - ›
6 * 2evaluates to 12
Postfix in Expressions
public class PostfixExpressions {
public static void main(String[] args) {
int x = 5;
int result = x++ * 2; // 5 * 2 = 10, then x becomes 6
System.out.println("x = " + x); // Output: x = 6
System.out.println("result = " + result); // Output: result = 10
}
}Evaluation:
- ›Current value (5) is used in expression:
5 * 2 = 10 - ›Then
xis incremented to 6
Complex Expression Examples
public class ComplexExpressions {
public static void main(String[] args) {
int a = 5;
int b = 10;
// Using pre-increment
int result1 = ++a + ++b; // a=6, b=11, then 6+11=17
System.out.println("a=" + a + ", b=" + b + ", result1=" + result1);
// Output: a=6, b=11, result1=17
// Reset
a = 5;
b = 10;
// Using post-increment
int result2 = a++ + b++; // 5+10=15, then a=6, b=11
System.out.println("a=" + a + ", b=" + b + ", result2=" + result2);
// Output: a=6, b=11, result2=15
// Reset
a = 5;
b = 10;
// Mixed
int result3 = ++a + b++; // a=6, 6+10=16, then b=11
System.out.println("a=" + a + ", b=" + b + ", result3=" + result3);
// Output: a=6, b=11, result3=16
}
}Standalone vs In-Expression
Standalone Usage
When used alone, prefix and postfix are equivalent:
int x = 5;
x++; // x becomes 6
// Same as:
++x; // x becomes 6
// Both just increment x, no differencepublic class StandaloneDemo {
public static void main(String[] args) {
int count = 0;
count++; // count = 1
++count; // count = 2
count++; // count = 3
System.out.println("Final count: " + count); // Output: 3
}
}In Expressions - Big Difference!
When used in expressions, they behave differently:
public class ExpressionDifference {
public static void main(String[] args) {
int x = 5;
int y;
// Postfix - returns old value
y = x++;
System.out.println("Postfix: x=" + x + ", y=" + y);
// Output: x=6, y=5
// Reset
x = 5;
// Prefix - returns new value
y = ++x;
System.out.println("Prefix: x=" + x + ", y=" + y);
// Output: x=6, y=6
}
}With Loops
For Loop Examples
public class LoopExamples {
public static void main(String[] args) {
// Standard for loop - postfix is common
for (int i = 0; i < 5; i++) {
System.out.print(i + " "); // Output: 0 1 2 3 4
}
System.out.println();
// Prefix works the same in this context
for (int i = 0; i < 5; ++i) {
System.out.print(i + " "); // Output: 0 1 2 3 4
}
System.out.println();
// Decrement loop
for (int i = 5; i > 0; i--) {
System.out.print(i + " "); // Output: 5 4 3 2 1
}
}
}While Loop Examples
public class WhileLoopDemo {
public static void main(String[] args) {
int count = 0;
// Using postfix
while (count < 5) {
System.out.println("Count: " + count);
count++; // Increment at end of loop
}
// Output: Count: 0, 1, 2, 3, 4
// Using prefix (same result)
count = 0;
while (count < 5) {
System.out.println("Count: " + count);
++count; // Increment at end of loop
}
}
}Difference in Loop Condition
public class LoopConditionDemo {
public static void main(String[] args) {
int i = 0;
// Using postfix in condition
while (i++ < 5) {
System.out.print(i + " "); // Output: 1 2 3 4 5
}
// i is compared (0<5, 1<5, ...), THEN incremented
System.out.println();
i = 0;
// Using prefix in condition
while (++i < 5) {
System.out.print(i + " "); // Output: 1 2 3 4
}
// i is incremented, THEN compared (1<5, 2<5, ...)
}
}With Arrays
Array Traversal
public class ArrayTraversal {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
// Using postfix (most common)
int i = 0;
while (i < numbers.length) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
i++;
}
// Using array with increment in access
int[] data = {5, 10, 15, 20};
int index = 0;
System.out.println(data[index++]); // Prints 5, then index becomes 1
System.out.println(data[index++]); // Prints 10, then index becomes 2
System.out.println(data[index++]); // Prints 15, then index becomes 3
}
}Array Index Manipulation
public class ArrayIndexDemo {
public static void main(String[] args) {
int[] arr = {100, 200, 300, 400, 500};
int i = 0;
// Post-increment - use current, then increment
System.out.println(arr[i++]); // Prints arr[0]=100, then i=1
System.out.println(arr[i++]); // Prints arr[1]=200, then i=2
System.out.println(arr[i++]); // Prints arr[2]=300, then i=3
// i is now 3
// Pre-decrement - decrement, then use
System.out.println(arr[--i]); // i=2, prints arr[2]=300
System.out.println(arr[--i]); // i=1, prints arr[1]=200
}
}Common Mistakes
Mistake 1: Confusing Prefix and Postfix
public class CommonMistake1 {
public static void main(String[] args) {
int score = 0;
// ❌ WRONG - Expecting 1, but gets 0
int currentScore = score++;
System.out.println("currentScore: " + currentScore); // Output: 0
System.out.println("score: " + score); // Output: 1
// ✅ CORRECT - If you want the incremented value
score = 0;
currentScore = ++score;
System.out.println("currentScore: " + currentScore); // Output: 1
System.out.println("score: " + score); // Output: 1
}
}Mistake 2: Multiple Increments in One Statement
public class CommonMistake2 {
public static void main(String[] args) {
int x = 5;
// ❌ WRONG - Undefined behavior
// x = x++; // Don't do this!
// ✅ CORRECT - Use separately
x = x + 1;
// Or simply:
x++;
}
}Mistake 3: Using in Complex Expressions
public class CommonMistake3 {
public static void main(String[] args) {
int a = 5;
// ❌ CONFUSING - Hard to understand
int result = a++ + ++a + a++;
// Avoid this! Very hard to debug
// ✅ BETTER - Break into steps
a = 5;
int b = a;
a++;
int c = ++a;
int d = a++;
result = b + c + d; // Clear and maintainable
}
}Mistake 4: In Function Arguments
public class CommonMistake4 {
public static void printNumbers(int x, int y, int z) {
System.out.println(x + ", " + y + ", " + z);
}
public static void main(String[] args) {
int count = 1;
// ❌ CONFUSING - Order of evaluation unclear
// printNumbers(count++, count++, count++);
// ✅ BETTER - Increment separately
printNumbers(count, count + 1, count + 2);
count += 3;
}
}Mistake 5: Expecting Different Behavior Standalone
public class CommonMistake5 {
public static void main(String[] args) {
int x = 5;
// These are IDENTICAL when used standalone:
x++; // x becomes 6
x = 5;
++x; // x becomes 6
// No difference! Only matters in expressions.
}
}Practical Examples
Example 1: Counter
public class Counter {
private int count;
public Counter() {
this.count = 0;
}
public int increment() {
return ++count; // Increment and return new value
}
public int decrement() {
return --count; // Decrement and return new value
}
public int getCount() {
return count;
}
public static void main(String[] args) {
Counter counter = new Counter();
System.out.println("Increment: " + counter.increment()); // 1
System.out.println("Increment: " + counter.increment()); // 2
System.out.println("Increment: " + counter.increment()); // 3
System.out.println("Decrement: " + counter.decrement()); // 2
System.out.println("Count: " + counter.getCount()); // 2
}
}Example 2: Array Pointer Movement
public class ArrayPointer {
public static void main(String[] args) {
int[] data = {10, 20, 30, 40, 50};
int pointer = 0;
// Move forward
System.out.println("Current: " + data[pointer++]); // 10, pointer=1
System.out.println("Current: " + data[pointer++]); // 20, pointer=2
System.out.println("Current: " + data[pointer++]); // 30, pointer=3
// Move backward
System.out.println("Current: " + data[--pointer]); // 30, pointer=2
System.out.println("Current: " + data[--pointer]); // 20, pointer=1
}
}Example 3: ID Generator
public class IDGenerator {
private static int nextID = 1000;
public static int generateID() {
return nextID++; // Return current, then increment
}
public static void main(String[] args) {
System.out.println("User ID: " + generateID()); // 1000
System.out.println("User ID: " + generateID()); // 1001
System.out.println("User ID: " + generateID()); // 1002
System.out.println("Next ID will be: " + nextID); // 1003
}
}Example 4: Stack Implementation (Simplified)
public class SimpleStack {
private int[] data;
private int top;
public SimpleStack(int size) {
data = new int[size];
top = -1; // Empty stack
}
public void push(int value) {
if (top < data.length - 1) {
data[++top] = value; // Increment top, then store
}
}
public int pop() {
if (top >= 0) {
return data[top--]; // Return current, then decrement
}
return -1; // Empty
}
public static void main(String[] args) {
SimpleStack stack = new SimpleStack(5);
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Pop: " + stack.pop()); // 30
System.out.println("Pop: " + stack.pop()); // 20
System.out.println("Pop: " + stack.pop()); // 10
}
}Best Practices
Increment/Decrement Best Practices:
1. Prefer Standalone Usage:
// ✅ GOOD - Clear and simple
count++;
total--;2. Avoid in Complex Expressions:
// ❌ BAD - Hard to understand
result = x++ + y++ * z--;
// ✅ GOOD - Break into steps
result = x + y * z;
x++;
y++;
z--;3. In Loops - Postfix is Standard:
// ✅ Standard convention
for (int i = 0; i < n; i++) {
// ...
}4. When You Need the Value - Choose Carefully:
// Need old value? Use postfix
int oldValue = count++;
// Need new value? Use prefix
int newValue = ++count;5. Never Modify Same Variable Twice:
// ❌ WRONG - Undefined behavior
x = x++;
result = ++i + i++;
// ✅ CORRECT - Separate statements
x++;
result = i + j;6. Be Explicit for Clarity:
// When in doubt, be explicit:
count = count + 1; // Always clear
// Instead of:
count++; // Only if the context is simpleRemember:
- ›Prefix:
++x→ Change first, use new value - ›Postfix:
x++→ Use current value, change after - ›Standalone: No difference between prefix and postfix
- ›In expressions: Big difference!
- ›Keep it simple: Avoid multiple operators in one statement
Quick Reference
Behavior Summary
| Operator | Name | Action | Returns |
|---|---|---|---|
++x | Pre-increment | Add 1 first | New value |
x++ | Post-increment | Add 1 after | Old value |
--x | Pre-decrement | Subtract 1 first | New value |
x-- | Post-decrement | Subtract 1 after | Old value |
When to Use Which
| Scenario | Recommended | Why |
|---|---|---|
| Standalone statement | Either | No difference |
| For loop increment | i++ | Convention |
| Need return value | Choose based on need | Prefix for new, postfix for old |
| Array index movement | arr[i++] | Get current, move forward |
| Counter that returns | return ++count | Return updated value |
| ID generation | return id++ | Return current, increment for next |
Congratulations! You now understand the subtle but important differences between prefix and postfix increment/decrement operators!
What to Read Next
Review all of Java's operator categories in one place.
Practice Programs
Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.
Applies unary plus, unary minus, and pre/post increment and decrement to a single variable.
Prints every number from 1 up to a given limit.
Prints every number from a given limit down to 1.