This section contains the detail about the Increment and decrement operator in java.
Increment and decrement operator
The ++ and -- are increment and decrement operator in java, respectively.
The increment operator increase its operand by one. The decrement operator decreases its operand by one. For example :
By using increment operator we can write
x = x +1;
as
x++;
Both have the same meaning.
In the same way, the statement
x = x-1;
has the same meaning as
x--;
These two operator can appear in post fix and prefix form but the output value is different in both cases.
In the prefix form, the operand is incremented or decremented before value is assigned to variable. In postfix form, the previous value is obtained for use in the expression or assigned to variable, and then the operand is modified.
For example :
x = 42;
y = ++x;
Here y = ++x
is equivalent to :
x = x+1;
y = x;
It means final value of "y" will be 43. Given below postfix form :
x = 42;
y = x++;
Here, y = x++ is equivalent to :
y = x;
x = x+1;
In this case, the final value of "y" will be 42. But in both cases x's final value is 43.
Example :
public class IncrementOperator { public static void main(String args[]) { int x = 1; int y = 2; int z; int k; z = ++y; k = x++; z++; System.out.println("x = " + x); System.out.println("y = " + y); System.out.println("z = " + z); System.out.println("k = " + k); } }
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac IncrementOperator.java C:\Program Files\Java\jdk1.6.0_18\bin>java IncrementOperator x = 2 y = 3 z = 4 k = 1 |
[ 0 ] Comments