Java Reference
In-Depth Information
Examine the following code and try to determine its output:
10. char c = 'A';
11. for(int i = 1; i <= 10; i++) {
12. System.out.print(c++ + “ “);
13. }
14. System.out.print(c);
The fi rst value printed is 'A' , then c is incremented, which results in 'B' printed on the
second iteration of the loop. In total, 11 char s are printed and the output is
A B C D E F G H I J K
The following code demonstrates use of the decrement operator. Examine the code and
try to determine its output:
16. int y = 5;
17. int result = y-- * 3 / --y;
18. System.out.println(“y = “ + y);
19. System.out.println(“result = “ + result);
I have to admit this is a tricky question! (I hope you never see code like this in the real
world.) Notice y is decremented twice, so the output of y is 3. The value of result is not
as obvious. Order of operations dictates that the multiplication is evaluated fi rst. The value
of y is 5, so 5*3 is 15. The multiplication is done, so the post-decrement occurs and y
becomes 4. Now the division is evaluated and y is pre-decremented to 3 before the division,
resulting in 15 / 3 , which is 5. The output of this code is
y = 3
result = 5
Make Sure You Understand the Increment and Decrement Operators
The exam has plenty of questions that use the prefi x and postfi x increment and decre-
ment operators. In many situations, the exam question is testing a different Java concept,
not the incrementing or decrementing of variables. Make sure you have a good under-
standing of these fundamental (and sometimes tricky) operators.
The Relational Operators
The following operators are referred to as the relational operators :
< : less than
<= : less than or equal
Search WWH ::




Custom Search