The pages of this web site are not formatted to conserve paper, but my new book (ISBN: 0-9745862-0-X) is formatted to save paper, save your printer cartridge, save a loose-leaf binder, and save money. If you prefer to work my exams from printed pages, then give your printer a rest and buy my new book.
Today, you can find my book at amazon.com.
| No. | Answer | Remark | |
|---|---|---|---|
| 1 | c | Prints: 195ab | Both operands of the first addition operator are promoted from type char to int, and are evaluated as integral numeric values. The right hand operand of the second addition operator is of type String, so the result of the first addition operator is converted to type String, and is concatenated with the right hand operand. As evaluation of the expression continues from left to right, the remaining operands are also converted to type String. |
| 2 | e | None of the above | Line 4 does not generate a compile-time error. The reference named base actually refers to an instance of type Sub, so the reference may be cast to type Sub. |
| 3 | d | Run-time error at line 2 | The compiler accepts the explicit cast at line 2, but an error is generated at run-time. Type Base is the super class of type Sub, so an instance of type Base can not be converted to the type of the subclass, Sub. |
| 4 | e | None of the above | Although the reference named base is of type Base, the instance that it refers to is of type Sub, and the reference can be cast to type Sub. Since instances of type Sub implement both interfaces, I1 and I2, the Sub type instances can be assigned to references of type I1 and I2 without an explicit cast. |
| 5 | d | 4 | The Object referenced by obj is of type Sub[], and the reference, base, is of type Base[]. The assignment expression, base = obj requires an explicit cast to type Base[] as follows: base = (Base[])obj. |
| 6 | f | Run-time error at line 3 | Base is the superclass of type Sub, so a reference to an actual instance of type Base can not be cast to type Sub. Therefore, a reference to an array instance of type Base[] can not be cast to type Sub[]. The type of the reference, obj, is Object. Type Sub[] is a subclass of Object. The compiler accepts the cast, because the actual instance referenced at run-time might be of type Sub[]. In this case, the actual type of the instance referenced by obj at run-time is found to be type Base[], so the result is a run-time error. |