Increment and Decrement Operators in JAVA
Posted by
Ravi Kumar at Friday, March 6, 2009
Share this post:
|
We know that one of the most common operations with a numeric variable is to add or subtract 1. ++ adds 1 to the current value of the variable, and -- subtracts 1 from it.
There are two forms of these operators. 1)postfix 2)prefix
Postfix: Postfix form of the operator that is placed after the operand (i++).
For example, the code
int i= 12;
i++;
changes i to 13.
Prefix: The prefix form is ++i. Both prefix and postfix change the value of the variable by 1. The difference between the two only appears when they are used inside expressions. The prefix form does the addition first; the postfix form evaluates to the old value of the variable.
Example:
int m = 7;
int n = 7;
int a = 2 * ++m; // now a is 16, m is 8
int b = 2 * n++; // now b is 14, n is 8
We can not apply increment operator to numbers themselves. 8++ is not a legal statement.