Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Prefix vs Postfix Increment: Semantics and Pitfalls

Understand the difference between Java's prefix and postfix increment operators, how their values behave in expressions, and where each form is appropriate.

~5 min readJava
#increment operators#Java operators#expression evaluation#side effects
Two arrows showing the difference between prefix and postfix increment in Java, one pointing right and one pointing left.

Semantics: What ++i and i++ Actually Do

The Java prefix vs postfix increment question comes down to when the value is used in the surrounding expression. Both ++i and i++ increase the variable by 1, but the value of the expression differs.

  • ++i (prefix) increments the variable first, then the expression evaluates to the new value.
  • i++ (postfix) evaluates to the old value, and the increment happens afterward.

In isolation, ++i; and i++; have identical effect on i. The difference only appears when the operator is embedded in a larger expression.

java
int a = 5; int b = ++a; // a becomes 6, b is 6 int c = 5; int d = c++; // d is 5, c becomes 6

It can help to think of the evaluation order. For b = ++a, evaluating ++a increments a to 6 and yields 6; that value is then assigned to b. For d = c++, evaluating c++ saves the old value 5, increments c to 6, and yields 5; the assignment then stores 5 into d.

Impact on Loop Control Variables

A common usage is in for loops, where i++ and ++i are often treated as interchangeable. The update expression in a for loop is executed as a standalone statement, so the expression value is discarded. There is no behavior difference.

java
for (int i = 0; i < 5; i++) { } for (int i = 0; i < 5; ++i) { }

Both loops iterate the same number of times. The choice is stylistic, not a correctness issue; pick one convention and apply it consistently.

Inside Compound Assignments and Expressions

The difference becomes significant when the operator appears as part of a larger expression, such as an assignment, method argument, or array index.

java
int[] numbers = {10, 20, 30}; int index = 0; int value = numbers[index++]; // value gets numbers[0], then index becomes 1 int index2 = 1; int value2 = numbers[++index2]; // index2 becomes 2, value2 gets numbers[2]

These two lines read completely different elements. Using the wrong operator leads to off-by-one bugs that can be hard to spot, especially when the variable has a short name like i.

Evaluation Order in Complex Expressions

Java evaluates binary-operator operands from left to right, and the side effect of an increment is tied to that evaluation. Consider this example:

java
int x = 1; x = x++ + ++x; // ???

Let's break it down:

  1. The left operand x++ evaluates to 1, and x becomes 2.
  2. The right operand ++x increments x to 3, and the expression evaluates to 3.
  3. The sum is 4, and that value is assigned to x.

So x ends up as 4. Such code is legal, but it is confusing and fragile. The Java Language Specification defines the order, but a human reader cannot easily trace it without mental simulation. Prefer breaking such logic into separate statements.

Common Mistakes and How to Avoid Them

One frequent mistake is using i++ in a condition where the updated value is used unexpectedly. For example:

java
int index = 0; while (index++ < array.length) { process(array[index]); // index is already incremented, so this skips 0 and reads past the end }

The increment in the condition changes the value seen by the body. If you want to use the current index and then advance, use a clearer form:

java
int index = 0; while (index < array.length) { process(array[index++]); }

If you write i++ as a standalone statement inside a loop body, the increment happens when that statement runs. If you embed i++ in a larger expression, the update occurs while evaluating that expression, so later statements in the same iteration already see the new value.

Performance: Is Prefix Faster?

There is no need to treat this as a performance optimization. For a standalone increment of a local variable, the old value is often unused, and the compiler or JIT can handle both forms the same way. In more complex expressions, either form may need to carry extra state depending on the context. Choose the form that expresses whether you need the old value; readability and correctness matter more than any speculative performance difference.

Using Increment in Streams and Modern Java

In modern Java, you often avoid explicit index variables altogether. Streams and IntStream.range make the increment operator less visible. When you see index++ inside a lambda or a stream operation, that is a code smell because it introduces shared mutable state and can produce inconsistent results with parallel streams.

java
// Avoid: shared mutable counter in a stream int[] counter = {0}; IntStream.range(0, 10).forEach(i -> process(counter[0]++)); // Prefer: use the stream's index directly IntStream.range(0, 10).forEach(i -> process(i));

Using the operator in this way makes the code harder to parallelize and harder to reason about. If you need an index, let the stream provide it.

Choosing Prefix or Postfix in Your Code

When writing new code, ask whether the current value or the updated value is needed.

  • Use i++ when you need the original value in the expression, for example array[i++].
  • Use ++i in all other cases, especially in for loops and standalone increments.

This simple rule keeps code clear and avoids accidental off-by-one errors. The Java Language Specification guarantees the behavior, so there is no ambiguity, but relying on that nuance in complex expressions hurts readability and maintainability.

A Useful Pattern: Cursor with Postfix

The most productive use of i++ is when reading a sequence and moving a cursor forward in the same step. For example, reading fields from an array or parsing a character buffer:

java
char[] buf = {'a', 'b', 'c'}; int pos = 0; char first = buf[pos++]; // read 'a', then advance to 1 char second = buf[pos++]; // read 'b', then advance to 2

This pattern is concise and expresses exactly the operation you want. It is a clear, controlled use of the postfix operator that does not obscure the logic.

Limits: When Not to Use Increment at All

There are situations where the increment operator should be avoided entirely. In concurrent code, operations like i++ are not atomic; multiple threads can interfere and cause lost updates. For thread-safe counters, use AtomicInteger or LongAdder instead.

java
// Not thread-safe private int clicks; public void increment() { clicks++; } // Thread-safe private AtomicInteger clicks = new AtomicInteger(); public void increment() { clicks.incrementAndGet(); }

Also remember that a single i++ is not an atomic read-modify-write operation. If you need to read and update a counter as one protected operation, guard the larger sequence with a lock or use a concurrent counter type.

The distinction between prefix and postfix is fundamental to Java, but it does not need to be a source of bugs. Use it deliberately, prefer ++i when the old value is irrelevant, and keep expressions simple enough that the side effect is obvious to the next reader.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.