Skip to content
Tutorials Center
My learning

Topics

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.

Java
int x = 5;
int a = x++;   // a is 5, x is 6
int b = ++x;   // x is 7, b is 7

Try it

Java Prefix versus postfix

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.

Java Types, wrapping and the hidden cast

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

Java
++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 like x = (T)(x + 1) where T is the type of x. That is why byte b = 127; b++; compiles and wraps to -128, while b = b + 1 would not compile.
  • Works on every numeric type including char, float and double, and on boxed types (Integer, Long, ...), which are unboxed and boxed again. A null wrapper throws NullPointerException.
  • Evaluation order is strictly left to right in Java, so data[pos++] = 99 uses the old pos as the index. Even so, mixing several ++ on the same variable in one expression is hard to read; avoid it.
  • n = n++ leaves n unchanged. 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. Use AtomicInteger.incrementAndGet() or a lock when several threads update it.
  • Prefer the plain form in statements (i++;) and in for updates. Use the value of the expression only when it makes the code shorter and still clear.
  • Overflow wraps silently for int and long. See Integer overflow.