Java Reference ยท Operators
Java increment and decrement operators
Reference for the Java increment (++) and decrement (--) operators: prefix versus postfix, the value of the expression, and classic pitfalls.
The increment operator ++ adds 1 to a numeric variable and the decrement operator -- subtracts 1. Each comes in two forms. In the prefix form (++x) the variable is changed first and the expression's value is the new value. In the postfix form (x++) the expression's value is the old value, and the variable is changed afterwards.
When the result is not used, as in a for loop update, both forms do the same thing. The difference only shows when you read the value of the expression itself.
int x = 5; int a = x++; // a is 5, x is 6 int b = ++x; // x is 7, b is 7
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
++variable // pre-increment variable++ // post-increment --variable // pre-decrement variable-- // post-decrement
| Form | Value of the expression | Variable afterwards |
|---|---|---|
++x |
x + 1 |
x + 1 |
x++ |
x (before) |
x + 1 |
--x |
x - 1 |
x - 1 |
x-- |
x (before) |
x - 1 |
The operand must be a variable: a local, a field, an array element, or a boxed variable. 5++ or (a + b)++ does not compile.
Usage notes
- Hidden cast.
x++behaves likex = (T)(x + 1)whereTis the type ofx. That is whybyte b = 127; b++;compiles and wraps to-128, whileb = b + 1would not compile. - Works on every numeric type including
char,floatanddouble, and on boxed types (Integer,Long, ...), which are unboxed and boxed again. Anullwrapper throwsNullPointerException. - Evaluation order is strictly left to right in Java, so
data[pos++] = 99uses the oldposas the index. Even so, mixing several++on the same variable in one expression is hard to read; avoid it. n = n++leavesnunchanged. The incremented value is overwritten by the saved old value.- Not atomic.
counter++on a shared field is a read, an add and a write. UseAtomicInteger.incrementAndGet()or a lock when several threads update it. - Prefer the plain form in statements (
i++;) and inforupdates. Use the value of the expression only when it makes the code shorter and still clear. - Overflow wraps silently for
intandlong. See Integer overflow.