JavaBasic syntax and simple programsOperations on primitive types

Increment and decrement

3 seconds read

In this topic, we will discuss one of the most famous operators in programming - increment. This operation is used in many programming languages (including Java) to increase a variable by one. It is interesting this operation is used in the name of C++, and signifies the evolutionary nature of the changes from C.

Using ++ and -- in Java

Java has two opposite operations called increment (++) and decrement (--) to increase/decrease the value of a variable by one.

int n = 10;
n++; // 11
n--; // 10

The code above is actually the same as below.

int n = 10;
n += 1; // 11
n -= 1; // 10

Prefix and postfix forms

Both increment and decrement operators have two forms which are very important when using the result in the current statement:

  • prefix (++n or --n) increases/decreases the value of a variable before it is used;
  • postfix (n++ or n--) increases/decreases the value of a variable after it is used.

The following examples demonstrate both forms of increment.

Prefix increment:

int a = 4;
int b = ++a;

System.out.println(a); // 5
System.out.println(b); // 5
In this case, the value of a has been incremented and then assigned to b. So, b is 5.

Postfix increment:

int a = 4;
int b = a++;

System.out.println(a); // 5
System.out.println(b); // 4

In this case, the value of a has been assigned to b and then incremented by 1. So, b is 4.

We hope, you clearly understand what is increment and decrement as well as both their forms.
4 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo