Increment and decrement operators
- In Java increment and decrement operators are used to increase or decrease the value of a variable by 1.
- The following two operators are the increment and decrement operators used.
Operator | Explanation |
---|---|
++ | Used to increase the value of a variable by 1. |
– | Used to decrease the value of a variable by 1. |
- Now let’s see how to use them
i++; // This is used to increase the value of variable 'i' by 1.
i--; // This is used to decrease the value of variable 'i' by 1.
i++;
// Is similar to,
i = i + 1;
i--;
// Is similar to,
i = i - 1;
- An interesting fact is that increment and decrement operators can appear in postfix form and the prefix form.
- Postfix form means when the increment or decrement operator is placed after the variable.
- Prefix form means when the increment or decrement operator is placed before the variable.
- Both methods performs the same function in a slightly different way.
i++; // Postfix
++i; // Prefix
- The only occasion we can experience the difference is when we call the output of the operator.
- The ‘postfix’ form will give the value of the variable as an output after the increment, while the ‘prefix’ form gives the output value of the variable before the increment.
- The following example will explain that.
// Postfix
int x = 5;
System.out.println("Postfix output = " + x++);
// Prefix
int y = 5;
System.out.println("Prefix output = " + ++y);
Postfix output = 5 Prefix output = 6
Which one of the following can be used instead of “i += 1”.