Skip to lesson

Increment and decrement: ++ and --

++ 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

Counter.javaJava
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);    }}
Output
Likes: 100
Seats left: 1

What this code does

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?

public class PrePost {
public static void main(String[] args) {
int a = 5;
int b = a++;
System.out.println("a = " + a + ", b = " + b);
int c = ++a;
System.out.println("a = " + a + ", c = " + c);
}
}

Variables

a
5

Output

(nothing printed yet)

Line 3a starts at 5.

Step 1 of 5
Use one ++ 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

Rowx beforeprintedx 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

InPrint.javaJava
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);    }}
Output
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