Java TUTORIAL - Increment Decrement operator
Similar to C/C++, Java provides Increment and decrement operator that increases or decreases the value of a variable by one. These are denoted by ++ and -- respectively.
If x has a value of 5, the statement
x++;
increases its value by 1. The value of x now becomes 6.
Similary the statement
x--;
will decrease the vale of x by one;
|
If you compile and run this program, you will get the output as follows
C:\Program Files\Java\jdk1.7.0_17\bin>java incdec The val of x after one increment 10 The val of x after two more decrements 8 |
You can also use the increment operator before the variable. So you may use ++x in place of x++ or --x in place of x--. It will not change the value finally assigned to x. So the following program gives the same output.
|
However, the things change when you assign the pre or post incremented variable to another variable. Take a look at the following two examples.
|
|
The first one ( y = ++x;) sets the value of y to 10 while in the second one ( y = x++; ) the value of y stays the same at 9. Keep in mind y =x++; means assign value of x to y and then increment the value of x by 1. The statememt y = ++x; means increment the value of x by 1 and then assign its value to y. Exercise 3
What is the value of y printed in the following code
|
Answer : 9