Java Reference
In-Depth Information
Answers to Review Questions
1.
C.
The code compiles and executes successfully, so A and B are incorrect. The com-
parison on line 6 is byte comparison, because
b1.byteValue()
is a byte and
b2
is auto-
matically unboxed to a byte. Because both bytes are
-12
, the comparison is true and
line 7 outputs
equal
. Therefore, the answer is C.
2.
D. The code compiles fi ne, so C is incorrect. On line 5, the Integer x is automatically
unboxed into an int. However, x is null in this program because it is an uninitialized fi eld
of Unboxer. Attempting to unbox a null reference results in a NullPointerException, so
the answer is D.
3.
A. The code compiles fi ne, so C and D are incorrect. Line 12 invokes the overloaded
doSomething method and passes in a byte argument, which is a valid argument for both
doSomething methods. The compiler has to pick one, and it chooses the method with the
nearest compatible parameter, which is the int parameter of the doSomething method on
line 2. Therefore, the output is method one and the answer is A.
4.
E. The parse method in the NumberFormat class throws the checked exception
ParseException, which must be handled or declared. The code does neither, so a
compiler error occurs on line 9 and therefore the answer is E.
5.
A and C.
D is incorrect: the
File
class contains a
mkdir
and
createNewFile
method
used for creating new directories and fi les on the fi le system. Because we are assum-
ing that the current directory does not contain any subdirectories, the
./test/
subdirectory cannot already exist. Therefore, line 8 is
true
and line 9 creates a new
subdirectory named
test
. The only reason line 13 would fail is if the fi le
something.
txt
already existed in
/test
, but because
/test
is a new, empty directory, the
createNewFile
method is successful and a new fi le named
something.txt
is
created in the
/test
subdirectory. Therefore, the answers are A and C.
6.
A, B, and E. String literals are automatically instantiated into String objects, so A is true.
B is also true; the two classes contain the same methods. The only difference between
StringBuilder and StringBuffer is that StringBuffer is thread-safe, which is why C
is false. You should use StringBuffer if using mutable strings in a multithreaded applica-
tion. D is false; the StringBuilder and StringBuffer classes represent mutable character
sequences. E is true; a StringBuffer and StringBuilder can grow and shrink to match
the number of characters in the sequence.
7.
B.
The code compiles fi ne, so E is incorrect. Line 7 is a valid statement and evaluates
to
true
, so
one
is output. The reference
s
points to a
String
object in the string pool
and
t
points to a
String
object on the heap. Because
s
and
t
do not point to the same
object in memory, line 11 is
false
. Line 15 is
true
because
s
and
t
both point to a
Hello
string. Therefore, the output is
onethree
and the answer is B.
Search WWH ::
Custom Search