It is used to decrement the value of an operand by 1. The operator is represented by a pair of minus operators (--). The operator can be applied before or after an operand.
Pre-decrement Operator: If a decrement operator is written before (prefix) the operand is known as pre-decrement. In such a case, the value is first decremented by 1 and then used for the computing purpose.
Syntax:
- --operand
Example: Suppose x=9, then the value of --x will be 8.
Post-decrement Operator: If a decrement operator is written after (postfix) the operand is known as post-decrement. In such a case, the value is first used and then decrements by 1.
Syntax:
- operand--
Example: Suppose x=11, then the value of x-- will be 10.
Let's use the pre-decrement and post-decrement operators in a Java program.
PrePostDecrementExample.java
- public class PrePostDecrementExample
- {
- public static void main(String args[])
- {
- int i = 10;
- i--;
- //prints 19
- System.out.println(i);
- --i;
- //prints 18
- System.out.println(i);
- //prints 17
- System.out.println(--i);
- //prints 17
- System.out.println(i--);
- //prints 16
- System.out.println(i);
- }
- }
Output:
19
18
17
17
16