The ++ and the – – are Java’s increment and decrement operators. ++ is used to increase the value by 1 and – – is used to decrease the value by 1. There are two kinds of Increment and Decrement Operators.
They are:
- Post-Increment or Post-Decrement:
First, the value is used for operation and then incremented or decremented. Represented like a++ or a–. - Pre-Increment Pre-Decrement:
Here First the value is incremented or decremented then used for the operation. Represented like++a
or – –a.
Example on Increment and Decrement Operator in java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //This program demonstrates the ++ and -- operators. public class IncrementDecrement { public static void main(String[] args) { int number = 10; //Original Value System.out.println("Original value: " + number); //Incrementing the number. number++; //Value after incrementing System.out.println("After Incrementing: " + number); // Decrement number. number--; // Display the value in number. System.out.println("Again, after decrementing " + number); } } |
Output: After execution following result will be displayed.
1 2 3 | Original value: 10 After Incrementing: 11 Again, after decrementing 10 |
Limitations of Increment and Decrement Operators:
Increment and decrement operators can only be applied to variables but not on constant values. If we apply on canstants then we will get a compile-time error.
1 2 | int x = 10; int y = ++10; // this will through compile-time error. |
Example of Pre increment and Post increment in java:
1 2 3 4 | a = 4; i = ++a + ++a + a++; i = 5 + 6 + 6; (a = 7) |
The above shows the use of a++ and ++a and at the end, if you print the value of a, you will get 7 as the value of a.
Pre-increment: (++a)
The major point to remember is that ++a
increments the value and immediately returns it.
Post-increment: (a++)
a++
also increments the value but returns an unchanged value of the variable. It does not return the value immediately but if it is executed on the next statement then a new value is used.
Example of Pre decrement and Post decrement in java:
1 2 3 4 | a = 4; i = --a + --a + a--; i = 3 + 2 + 2; (a = 1) |
Pre-decrement: (—a)
The major point to remember is that ––a
decrements the value and immediately returns it.
Post-decrement: (a—)
a––
also decrements the value but returns an unchanged value of the variable. It does not return the value immediately but if it is executed on the next statement then a new value is used.