Page 897 - AP Computer Science A, 7th edition
P. 897

7. (E) Choice D fails because you can’t compare an Integer to an Object. You need to cast ob to Integer, as is done in choice E, the correct answer. Choice D will give the error message
compareTo(java.lang.Integer) in java.lang.Integer cannot
be applied to (java.lang.Object)
Choice C will cause a ClassCastException since the calling and parameter objects are incompatible types. The compareTo method will try erroneously to cast its parameter to the type of the object calling the method. Choice A almost works: It fails because the dot operator has higher precedence than casting, which means that ob.compareTo is parsed before ob is cast to Integer, generating a message that the compareTo method is not in class Object. Choice A can be fixed with an extra pair of parentheses:
if (((Integer) ob).compareTo(intOb) < 0) ...
Choice B causes the same error message as choice A: no compareTo method in class Object.





























































































   895   896   897   898   899