Increment and decrement: ++ and --
20 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)++ adds 1 to a variable and -- takes away 1. count++; is a short way to write count = count + 1;.
++ and -- on their own line
A post gets one more like. A train has one less free seat.
Increment ++ adds 1 to a variable, and decrement -- takes 1 away.
Example 1 · Likes and seats
public class Counter { public static void main(String[] args) { int likes = 99; likes++; System.out.println("Likes: " + likes); int seats = 3; seats--; seats--; System.out.println("Seats left: " + seats); }}Likes: 100 Seats left: 1
What this code does
likes++;adds 1, so 99 becomes 100.- Each
seats--;takes 1 away: 3 becomes 2, then 1. likes++;is the shortest form oflikes += 1, from Assignment and compound assignment (opens in a new tab).
Both work only on a variable. 5++ is an error, because the number 5 cannot change.
Prefix and postfix: which value is used?
A bank's token machine must give you the number it shows, then move on to the next one.
Write a++ (postfix) to use the old value and then add 1, or ++a (prefix) to add 1 and then use the new value.
On a line by itself, both just add 1; the difference shows only when the value is used in the same line. -- follows the same rule. Step through: b = a++ gives b the old value, while c = ++a gives c the new one.
Trace the code
b = a++ or b = ++a?
Variables
- a
- 5
Output
(nothing printed yet)Line 3a starts at 5.
++ or -- per variable per line. x++ + ++x compiles, but nobody can read it at a glance.Trace it line by line
A single println(x++) prints a value and changes x, so a run of such lines is easy to lose track of.
Track three things per line: x before, what is printed, and x after. The table traces the program below it.
Trace x line by line
Step 1 of 6
| Row | x before | printed | x after |
|---|---|---|---|
| x++ | |||
| x | |||
| ++x | |||
| x-- | |||
| x |
- x
- 10
x starts at 10. Each row is one println line. Track the value before, what is printed, and the value after.Example 2 · Inside println
public class InPrint { public static void main(String[] args) { int x = 10; System.out.println(x++); System.out.println(x); System.out.println(++x); System.out.println(x--); System.out.println(x); }}10 11 12 12 11
What this code does
- Postfix lines (
x++,x--) print before the change; the prefix line (++x) prints after it. - The plain
println(x)lines show the change the line before made.
Next step
Check your understanding
10 quick questions