Java Reference
In-Depth Information
System.out.println(a);
a = 6 ;
a /= 2 ;
System.out.println(a);
2.14 Increment and Decrement Operators
The increment operator (++) and decrement operator (- -) are for incrementing and
decrementing a variable by 1.
Key
Point
The ++ and —— are two shorthand operators for incrementing and decrementing a variable by
1 . These are handy because that's often how much the value needs to be changed in many pro-
gramming tasks. For example, the following code increments i by 1 and decrements j by 1 .
increment operator ( ++ )
decrement operator ( −− )
int i = 3 , j = 3 ;
i++; // i becomes 4
j——; // j becomes 2
i++ is pronounced as i plus plus and i—— as i minus minus. These operators are known as
postfix increment (or postincrement) and postfix decrement (or postdecrement), because the
operators ++ and —— are placed after the variable. These operators can also be placed before
the variable. For example,
postincrement
postdecrement
int i = 3 , j = 3 ;
++i; // i becomes 4
——j; // j becomes 2
++i increments i by 1 and ——j decrements j by 1 . These operators are known as prefix
increment (or preincrement) and prefix decrement (or predecrement).
As you see, the effect of i++ and ++i or i—— and ——i are the same in the preceding exam-
ples. However, their effects are different when they are used in statements that do more than
just increment and decrement. Table 2.5 describes their differences and gives examples.
preincrement
predecrement
T ABLE 2.5
Increment and Decrement Operators
Operator
Name
Description
Example (assume i
=
1)
preincrement
++var
Increment var by 1 , and use the
new var value in the statement
int j = ++i;
// j is 2, i is 2
var++
postincrement
Increment var by 1 , but use the
original var value in the statement
int j = i++;
// j is 1, i is 2
——var
predecrement
Decrement var by 1 , and use the
new var value in the statement
int j = ——i;
// j is 0, i is 0
var——
postdecrement
Decrement var by 1 , and use the
original var value in the statement
int j = i——;
// j is 1, i is 0
Here are additional examples to illustrate the differences between the prefix form of ++ (or
—— ) and the postfix form of ++ (or −− ). Consider the following code:
int i = 10 ;
int newNum = 10 * i++;
Same effect as
int newNum = 10 * i;
i = i + 1;
System.out.print("i is " + i
+ ", newNum is " + newNum);
i is 11, newNum is 100
 
 
 
Search WWH ::




Custom Search