Prefix and Postfix Increment and Decrement Operators in Java

kamande mwangi
2 min readMar 1, 2023

--

Increment and Decrement

Increment and decrement operators increase and decrease a number by one. Of course you can use += 1 or -= 1 but there is a better way to do this: Increment and decrement operations.

example:

 int num = 10;
num++;
System.out.println(num); // prints 11
num--;
System.out.println(num); // prints 10

The above code is the same as:

  int num = 10;
num += 1;
System.out.println(num); // prints 11
num -= 1;
System.out.println(num); // prints 10

From the above example you can see that increment ++ does the same as +=1 but in a simpler way. The same is true for decrement.

Increment and decrement operators are of two forms: prefix and postfix.

Prefix

Prefix operator changes the value before it is used. Let’s look at some examples.

Consider the following code:

int num = 5;
int a = ++num;
int b = --num;
System.out.println(num); // prints 5
System.out.println(a); // prints 6
System.out.println(b); // prints 5

In this code, we initialize a variable num with a value of 5. We the use the prefix increment operator ++ on num while initializing a. This means that a is assigned the value of num after it has been incremented by 1. So, a gets the value of 6 and num also becomes 6.

Similarly, we use the prefix decrement operator on num while initializing b. This means that b is assigned the value of num after it has been decremented by 1. So, b gets the value of 5 and num also becomes 5 again.

Postfix

Postfix operator changes the value after it has been used.

consider the following code:

int num = 5;
int a = num++;
System.out.println(num); // prints 6
System.out.println(a); // prints 5

In this code, we initialize a variable num with the value of 5. We then initialize another variable a with the value of num. However, we use the postfix increment operator ++ on num during the assignment of a. This means that a is assigned the original value of num (5), and then num is incremented by 1. So, num becomes 6.

Finally, we print the values of num and a. As num has been modified to 6, its value is printed as 6. a retains the original value assigned to it and is printed as 5.

Postfix decrement example

int num = 5;
int a = num--;
System.out.println(num); // prints 4
System.out.println(a); // prints 5

Another example:

int a = 10;
int b = 12;

b = b + a++;
int c = ++a + b;
System.out.println(a);
System.out.println(b);
System.out.println(c);

What do you think this code will print?

Conclusion

Remember prefix changes the variable before using it, and the postfix changes it after.

--

--

No responses yet