Chapter Table of Contents
Section Table of Contents
Besides binary operators, Java also has some unary operators, which only operate on 1 thing as opposed to 2 things. Four of those unary operators are the increment and decrement operators. These will be very useful when we get into the chapter about Loops, but it doesn’t hurt to learn about them now.
These operators increase or decrease a variable by 1, which is the same as += 1 or -= 1.
Post vs Pre
For the increment and decrement operators, the way they work depends on where you put them. If you put the operator before the variable it operates on, it is referred to as a pre-increment or pre-decrement operator, because the variable is incremented/decremented before any other actions.
On the other hand, if the operator is put after the variable, it is referred to as a post-increment or post-decrement operator, because the variable is incremented/decremented after any other actions.
Here’s an example:
int i = 1; int j; // increment j = ++i; // j is 2, i is 2 System.out.println("j: " + j + ", i: " + i); j = 1; // reset j = i++; // j is 1, i is 2 System.out.println("j: " + j + ", i: " + i); // decrement j = --i; // j is 0, i is 0 System.out.println("j: " + j + ", i: " + i); j = 1; // reset j = i--; // j is 1, i is 0 System.out.println("j: " + j + ", i: " + i);
Let’s break down this code. When the line
j = ++i runs, since the
++ is before the
i, it is a pre-increment operator. Therefore,
i is incremented, and then the current value of
i is assigned to
On the other hand, when the line
j = i++ runs, since the
++ is after the
i, it is a post-increment operator. Therefore, the current value of
i is assigned to
j, and then
i is incremented.
The same applies to the pre- and post-decrement operators.
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact firstname.lastname@example.org for inquiries.