Java Reference
In-Depth Information
Answers to Review Questions
1. E. 10%3 equals 1, so line 4 is false, which results in line 5 being skipped. I intentionally
omitted the curly braces from the if on line 4 and indented line 6 to throw you off. Line
6 executes and 1 is printed regardless because it is not a part of the if statement. Line 7 is
true, so one is also printed. Therefore, the answer is E.
2.
C. The code compiles fi ne, so A and B are incorrect. In an if-else statement, either the
true block or false block executes, so either x or y must be printed, which implies E is incor-
rect. On line 5, the boolean variable b is assigned to false because 5 is not less than 0.
Line 6 is an assignment, not a comparison. b is assigned to true on line 6 and the result of
the assignment is true, so line 7 executes and a 5 is printed. Therefore, the answer is C.
3. E. You cannot switch on a String. Line 4 generates a compiler error, so the correct answer
is E.
4. B. The code compiles fi ne, so D and E are incorrect. Assertions are enabled, but the
default case on line 13 does not execute, so C is incorrect. The Color is RED, so the case
on line 6 is satisfi ed and red is printed on line 7. There is no break, so line 9 executes and
blue is printed, so A is incorrect. Line 10 breaks out of the switch and the program is
done. The output is redblue, so the answer is B.
5
B. The code compiles fi ne, so C, D, and E are incorrect. The case on line 8 is satisfi ed, so
line 9 executes and great is printed. There is no break, so line 11 executes and passed is
printed and therefore A is incorrect. The switch breaks at line 12, so the fi nal output is
greatpassed and the answer is B.
6. A. The outer loop executes 3 times and the inner loop executes 3 times, so 9 characters
are printed starting with 'a', then 'b' and so on up to 'i'. Therefore, the output is
'abcdefghi' and the answer is A.
7. E. The int variable index is declared within the for statement, so its scope is only within
the for loop. Line 14 generates a compiler error because index is out of scope, so the
answer is E.
8. D. The code compiles fi ne, so E is incorrect. Line 3 creates an array of six ints. The
enhanced for loop adds the six ints together, so sum is 2+4+5+5+6+8=30. scores.length
is 6 and 30/6 equals 5, which is printed on line 8. Therefore, the answer is D.
9. B. The expression on line 8 is true when row * col is an even number. Let's step through
each iteration:
row = 1 and col = 1 : Line 8 is false , the continue is skipped, and count is
incremented to 1 .
row = 1 and col = 2 : Line 8 is true , the continue executes, and control jumps to
the next iteration of the outer for loop.
row = 2 and col = 1 : Line 8 is true again, so we jump to the next iteration of the
outer loop.
Search WWH ::




Custom Search