- ++ increment (prefix and postfix)
- -- decrement (prefix and postfix)
The operator is placed either before (prefix) or after (postfix) a variable to change its value. Whether the operator comes before or after the operand can change the outcome of an expression. Examine the following:
1. class MathTest {
2. static int players = 0;
3. public static void main (String [] args) {
4. System.out.println("players online: " + players++);
5. System.out.println("The value of players is " + players);
6. System.out.println("The value of players is now " + ++players);
7. }
8. }
Notice that in the fourth line of the program the increment operator is after the variable players. That means we're using the postfix increment operator, which causes players to be incremented by one but only after the value of players is used in the expression. When we run this program, it outputs the following:
%java MathTest
players online: 0
The value of players is 1
The value of players is now 2
Notice that when the variable is written to the screen, at first it says the value is 0. Because we used the postfix increment operator, the increment doesn't happen until after the players variable is used in the print statement. Get it? The "post" in postfix means after. Line 5 doesn't increment players; it just outputs its value to the screen, so the newly incremented value displayed is 1. Line 6 applies the prefix increment operator to players, which means the increment happens before the value of the variable is used, so the output is 2.
Expect to see questions mixing the increment and decrement operators with other operators, as in the following example:
int x = 2; int y = 3;
if ((y == x++) | (x < ++y)) {
System.out.println("x = " + x + " y = " + y) ;
}
The preceding code prints: x = 3 y = 4
You can read the code as follows: "If 3 is equal to 2 OR 3 < 4"
The first expression compares x and y, and the result is false, because the increment on x doesn't happen until after the == test is made. Next, we increment x, so now x is 3. Then we check to see if x is less than y, but we increment y before comparing it with x! So the second logical test is (3 < 4). The result is true, so the print statement runs.
As with String concatenation, the increment and decrement operators are used throughout the exam, even on questions that aren't trying to test your knowledge of how those operators work. You might see them in questions on for loops, exceptions, even threads. Be ready.
Given:
10. int x = 0;
11. int y = 10;
12. do{
13. y--;
14. ++x;
15. }while(x < 5);
16. System.out.print(x + "," + y);
What is the result?
A. 5,6
B. 5,5
C. 6,5
D. 6,6
沒有留言:
張貼留言