Appendix A

Answers to Review Questions

Chapter 1: Introducing the Basics of Java

1. A, D If you missed this one, please reread the chapter!

2. False

3. C Object equality is a tricky concept. It will serve you well to remember that two variables can point to the same object in memory. They had certainly better be equal! Whether two variables, pointing to objects that have the same content, are equal is something the class programmer has to encode. Keep that information in your back pocket for now.

4. A Each non-static member in an object belongs only to that object. Other objects of the same type maintain their own values.

5. A A wildcard applies only to the package listed, not to nested packages. It is also not a globbing mechanism; it only matches class files.

6. A The Java Virtual Machine adds some behind-the-scenes information. These values are called metadata. You don’t have to worry about this aspect of a class until you’re ready to look into the internals of the JVM.

7. B Review the discussion on variable lifetime if this answer is not clear to you.

8. D When arguments are input on the command line, they’re in the control of the shell. The shell doesn’t know what a String object is and uses unquoted or unescaped white space to separate the arguments.

9. True Remember, the Java compiler will add one if the programmer does not.

10. C The classpath is the final link between a Java program in runtime and the shell environment of your system. The program knows where to find classes by package declaration. The system has to know where to find the packages. Between the two, the JVM is able to locate files that are Java classes and then load them into memory.

Chapter 2: Applying Data Types in Java Programming

1. B The JVM must create this object as instructed. Without a reference, however, you can’t access it. It will be eligible for garbage collection right away.

2. D Immutable objects (referents) can’t be modified once they are created.

3. D The highest bit in any integral type’s range is reserved for the sign. That leaves 263 possible nonnegative and negative values. We use one in the nonnegative range for zero, leaving enough for 263–1 positive values.

4. B 256 is too large for a byte. Other integral types will have their bit ranges padded with zeroes.

5. D The initial capacity of a StringBuilder object is 16 plus the length of the string argument (here, 18 characters). For exams (and possibly some job interviews), you’ll be expected to know by heart some technical details of well-known classes. You can’t remember everything, but if we discuss a class in detail in this book, you should plan to study it thoroughly.

6. A, D In a String, the length is its capacity; only the room required by the caller is ever allocated. In a StringBuilder, the length value can be equal to or less than its capacity value, but never more. All empty Strings have a length of zero.

7. D Java is case sensitive. Java keywords are all expressed in lowercase, but integer isn’t one of them.

8. D The content of a StringBuilder referent is completely arbitrary: control codes, punctuation marks, white space, even nothing at all. They will all make valid objects.

9. B The String class interns a value on direct assignment for the first time only. Upon a subsequent assignment of the same literal, the reference is made to point to the already interned String.

10. C A primitive stores a copy of a literal value. An object reference stores a copy of a referent location in memory.

Chapter 3: Using Java Operators and Conditional Logic

1. B 231 – 1 is the maximum positive value for an int. Its bitwise complement is the maximum negative value, which is –231.

2. D The categories between Equality and Conditional (Bitwise and Logical) aren’t listed, but the order given is still correct.

3. A Shifting is the other category that has compound assignment support.

4. True The compiler cares if a switch statement is legal. Whether it is also useful is something only the programmer can define and control.

5. C The parentheses change the order of evaluation but not the result. This expression evaluates to 37 before shifting, and then is right-shifted once to get 74.

6. C This question is tricky but instructive. The problem isn’t precedence; we know the postfix operator comes first. The result of that operation, however, is a value, not a variable. The variable isn’t in play anymore, so the subsequent operation becomes --2, not --x. Consequently, the compiler will tell you it expected a variable, not a value, and bail out.

7. B A switch test expression may evaluate to any integral type (except long), or their object-based counterparts, or a String. Boolean values are not supported.

8. True An enthusiastic person might contend that by modifying the source code of the Object class, you could make the correct answer False. Hypothetical dodges like that aside, the Object class by design maintains no difference between strict and effective equality. Every subclass may define effective equality as it sees fit, or not. Many classes, especially test cases like the ones we’ve written, have no need for it.

9. True The conditional operator is an expression that will return any legal type. In this case, what constitutes a legal type is defined by the variable used to accept the value.

10. False All if/else constructs are considered statements. The semicolon may always be replaced by code block separators, even if they contain one statement. The switch structure is also a statement, but allows only code block separators.

Chapter 4: Using Java Arrays

1. True Every array is a direct subclass of Object, regardless of its component type, and has access to all Object methods.

2. C Option B may be a crime against nature, but the compiler allows it. Option C uses the variable name as if it were a type, which is clearly illegal.

3. True A String object is considered equivalent to a char array that has the same content.

4. C Anonymous arrays aren’t nameless in any respect you’ve learned. They aren’t exceptions either. They actually restore the rules for expressions so an array can be created as part of any expression.

5. False There are several other validating rules that System.arraycopy() applies, including the rule that the arrays must have matching component types.

6. D Capacity is a secondary property of the ArrayList class. The methods ensureCapacity() and trimToSize() let you modify it, but only with respect to the array it contains.

7. B Lists order their components by indexing them. Duplicate values are possible because the index provides an implied key for each component.

8. True An array is a direct subclass of Object. It does not change any Object behavior, including the equals() method, which just implements the == operator.

9. True The documentation for ArrayList specifies its rules for equality, which it inherits. If two ArrayList objects have the same components in the same order, they are equal.

10. C You probably cannot answer this question correctly without writing test code for each assertion. That’s what I did. This isn’t really a review question, which perhaps doesn’t seem fair. There is, however, a very important moral: Never assume a class is robust, that it covers edge cases and other ugliness so you don’t have to. To use a Java class with complete confidence, you have to treat it skeptically. Always set out to prove with test code that it does what you think it does.

Chapter 5: Using Loops in Java Code

1. True That’s all it takes. An empty statement, signified by the semicolon, is sufficient under the compiler rule “It’s okay if it’s useless, so long as it’s legal.”

2. A, B The legal options are infinite loops, each ghastly in its own style. Option A produces an “unreachable code” error.

3. D The expression while (false) does not create unreachable code in a do/while loop, therefore the compiler allows it. The program will terminate shortly after it is started.

4. C To better understand the answer, print out the value of count before and after its value changes.

5. C The term iterating formally describes the process of traversing a Collections type but also applies to all loop constructs.

6. B The for-each construction handles an array of any length the same way, including zero length.

7. A The for statement does not open a code block, so only the println() method is part of that statement. The compiler complains because the break statement is not part of a switch or loop.

8. False These structures help clarify the programmer’s intent. There is no appreciable difference in performance.

9. D See the syntax presented in the text if you are unsure.

10. False You can define a collection object however you like. It won’t work with a for-each construct, however, unless it conforms to the Collections framework defined in the java.util package.

Chapter 6: Encapsulating Data and Exposing Methods in Java

1. C The final keyword disallows further change to the class or member it is applied to. Subclassing is the way Java defines allowing change to a class, so a final class cannot be subclassed.

2. False The protected modifier adds subclasses to what would otherwise be package-private visibility.

3. B, D The classpath merely names directories where packages reside. A package declaration should not overlap this location but rather should detail the location of classes underneath it.

4. False Classes from other packages can see such a class; they just can’t do anything with it.

5. C A final class can’t be subclassed but has no effect on method behavior. Mutability isn’t subject to just public methods, but to methods that change a field’s value. Any method that changes the data, regardless of its name, is a mutator. Naming a method with set merely advertises the idea.

6. A, B, C Once we start using packages, we have a number of requirements to observe. You can’t see a class in another package unless it is public and your class imports it. The environment must support the classpath at compilation time as well as runtime.

7. False A package is one scope. Every modifier applies equally to all classes in the same package.

8. D Option D, as described, leaves its implementation completely open. You can’t get much more abstract than that. Option A only suggests data hiding, while option B is a bean implementation. Option C is meaningless.

9. B Type-safety is controlled by the compiler, not by methods. Packaging just limits the exposure of a field unless it’s declared public. And an assignment to a field is, by definition, a mutation. What we can’t do without a method is limit the range of an otherwise type-safe assignment.

10. False A classpath is like a path environment variable. You can supply multiple directories, which will be checked in listed order, to resolve import statements.

Chapter 7: Using Java Methods to Communicate

1. B, C The word const is reserved by the Java language and cannot be used. Identifiers can include numbers, but they can’t start with a number.

2. B, D To overload a method, you must vary its parameter list. You can change the number, type, and/or order of the parameter list. Option B changes only the parameter name. Option D changes only the return type.

3. C Chaining isn’t a compiler-sensitive activity, just a term for a technique that makes overloading a method a little easier to manage. Common sense keeps you from calling every method in a class from every other method, but it’s perfectly legal.

4. A, D void is a return type, not a modifier; and package private is a stand-in term, not a keyword. All nonaccess modifiers are listed in Table 7-1.

5. D The number, type, and order of parameters all affect overloading.

6. C A functional method behaves like a function in that it returns a value based on (or calculated from) the parameters it receives. Option D is wrong because the definition does not restrict the type of return. Option A is wrong because the logic does not have to concern math. Option B describes an accessor method better than a functional one.

7. A See Table 7-2 for the descriptions. I described a procedure as a method that performs what its name suggests: no input, no returned type. A mutator uses the parameters it accepts to change a specific aspect of the object. Remember, these categories are not hard-and-fast Java rules. They are terms we’re using to better define the kinds of methods we write.

8. A, B All parameters are passed by their value. It’s just that primitive values and reference values aren’t the same kind of thing.

9. False A static method cannot call a non-static method unless it has an instance, or object context, to use. The reverse is not true. An object of a class follows its static members in load order, so they are always available to it.

10. False A static method can call non-static methods, but only if it has an object reference.

Chapter 8: Using Java Constructors

1. D Statements A and B apply to all constructors. Statement C is true of all default constructors as well as many others.

2. A, B, D You can apply only access modifiers to a constructor.

3. False The compiler writes a default constructor in a class only if no other is present. So long as there is one constructor in the code, the default constructor is not required.

4. B The this keyword refers to the current object. You can use it to access members and as a parameter in a method call.

5. False If there is an explicit, parameterized constructor in a class, the compiler does not write in a default constructor. Therefore, the call would fail. You’d have to write in a no-arg constructor for this() to work.

6. B The call this() is only acceptable as the first statement in a constructor body.

7. A You can use the new keyword in any method or constructor. Option B is wrong: You can’t use the this() call inside the constructor you’re trying to call (try it!). Option C is also wrong: If you declare a constructor private, the compiler does not check to see if you have a static method. Without one, the class is useless, but it will compile. Option D is also wrong: If you can’t see the class from outside the package, it won’t matter what visibility its constructor has.

8. True Even though it has a specific purpose, a main() method is still a class member. It cannot access non-static members without an object reference, but it can access any constructor.

9. B Encapsulation describes any class element you can hide behind a method to control how it’s accessed.

10. A, C A default-access constructor is visible to any class in its package (or file).

Chapter 9: Inheriting Code and Data in Java

1. C, D Option A is, of course, false; type-safety applies to all classes regardless of how you use them. Option B is false; a class can access protected members of another class if they reside in the same package. A subclass can override any non-final member from its parent or overload any method. Composed classes can be wrapped only by the containing class.

2. C You can overload any method you can see. The parameter list separates one method from others that have the same name, not the same modifiers. You can reuse the name of a static method in a parent class so long as the new method is also static. You can declare a method both final and static; they are not mutually exclusive modifiers. But you can’t override a method you can’t see; you can only reuse the method name.

3. True Try it! The final modifier doesn’t do anything useful for a main() method. It also does no harm. The compiler and the JVM don’t mind.

4. D Options B and D are correct, but D explains why. The instanceof operator tests the type of the referent. If obj is assigned the value null, it does not refer to any type. The test in that case evaluates to false.

5. A Options B, C, and D are common misunderstandings of the @Override annotation’s job. The compiler normally accepts an overridden method silently. This annotation ensures that you’ve actually executed an override, not an overload. It also helps you distinguish between true overriding and merely reusing the name of a method in any parent class that was declared private or static.

6. True A subclass constructor always invokes a super() call, whether it’s implied or stated in code. If a class doesn’t allow construction from a caller, it might as well be declared final. The compiler reports the problem differently but the effect is the same. There is an exception of sorts to this rule. If a class with private constructors has an inner class, the inner class may extend its containing class. Inner classes are a peculiar hybrid; they are part class and part class member. Since they live inside a class, they have the same visibility to that class’s private constructors any member method would.

7. B The super and this keywords apply to an object’s context, but they are not class members. You can use them only to refer to the current object. The remaining options are therefore moot.

8. A or D My technical editor is going to hate this question and call it dirty pool. He’s right. Polymorphic effect, in my view, is more a product of art than craft in object-oriented programming. You probably need to pass a test on this topic, but I can’t really help with an objective question. Option A is a reasonable, affirmative answer. Option D is a reasonable, dour answer. The quality of polymorphic effect you can achieve depends on how well you apply a common, intended meaning to the methods you override. Options B and C are out because you must have a type relationship and it does not have to be confined to a package.

9. C To achieve a useful type system, you start with general behavior or attributes in your parent classes and specialize them in your child classes. Granted, proper organization can be a matter of perspective. For these types it’s easy to rationalize the Employee class as the most general type. A manager, director, or executive “is-a” kind of employee. Thinking the other way around requires a qualification of some sort, as in “an employee could be a manager, director, or executive.” By the same token, you can say “a manager has one or more employees,” which brings to mind composition as the best way to express that relationship in Java code.

10. True The @Override annotation makes sure the current method is an override. The final modifier prevents a subclass from overriding it.

It may seem odd that you can override a method but prevent subclasses from doing the same. You can in fact prevent subclasses from implementing the toString() and equals() methods you have overridden. You can apply that technique for the better or for the worse, as I see it. It’s up to the programmer to apply this knowledge well. Just remember that you can make a method always visible by declaring it public, but you can’t make it always open to overriding.

Chapter 10: Understanding Java Interfaces and Abstract Classes

1. A Option A is correct because an interface method cannot have default access; the compiler will make it public whether it is declared or not. Abstract methods can be public too, so that’s not a difference. Any method can be overloaded, regardless of declaration.

2. True If you declare an interface method protected, the compiler will complain.

3. B, C To answer this question, you just need to look up the interface list for the java.lang package. The Serializable interface is listed in the java.io package. The List interface is listed in the java.util package.

4. False An interface is a type; you cannot test one as an instance of any type. However, an object made from a class that implements an interface will pass an instanceof test.

5. C Options A and B are missing a return type. Option D uses null as a return type, which is not a legal declaration.

6. A, D The String class is the return type and has no effect on parameter types. It is also declared final. An enum, while similar in some respects to an interface, cannot be implemented.

7. False Interface methods are always public, whether you declare the access modifier or not.

8. D Passing an enum element to System.out.println() invokes toString() on the element, which evaluates to the element name.

9. True Interface methods are abstract methods. It’s considered bad style to include the modifier when writing an interface.

10. A An interface with no methods to implement is also called a marker interface. If a class implements it, it qualifies as that type. The java.io.Serializable interface is an example of a marker interface that is essential to converting objects into a stream of bytes.

Chapter 11: Throwing and Catching Exceptions in Java

1. B Option A is incorrect because you can declare any exception; the only standard is whether it’s reasonable to do so. Option C is wrong for the same reason. Option D is wrong because the Throwable class has no particular restrictions to it. There’s no need for another kind of Throwable category, but the compiler and JVM do not prohibit you from making one.

2. C Options A and D descend from the RuntimeException class. Option B descends from the Error class. Option C descends from the IOException class, which descends from the Exception class.

3. True Multi-catch syntax prohibits any two exception types that have a parent-child relationship. You could combine Error and Exception in a multi-catch clause if you wanted to. Again, the standard is what’s reasonable.

4. D Options A, B, and C are wrong because all descendants of the Throwable class inherit the Serializable interface.

5. False The JVM will only throw objects that descend from the Throwable class. It does not impose any restrictions that keep you from passing them around like regular objects. It’s unreasonable to use exceptions this way—but not illegal.

6. A You’re never required to use a finally block. Its purpose is to bring control back to a common point from all possible paths of execution, including exceptions that are raised during exception handling.

7. C The code violation occurs in the second statement, which tries to cast the Integer object to a String object. Removing that line and replacing the argument to the println() method with the obj reference solves the problem. There are no other untoward operations in this code.

8. D The compiler tests the operation for a valid type, but not a valid result, so the code will still compile and run. At runtime, evaluating the parameter will precede passing it to the println() method, so an ArithmeticException object is raised. It’s reasonable to infer that the result is also an illegal argument, but the order of evaluation determines which exception would occur first.

9. A Option B is wrong because the ClassCastException class descends from the RuntimeException class. Option C is wrong because the RuntimeException class descends from the Exception class.

10. C According to the class documentation, this exception is a member of the Java Collections Framework, which resides in the java.util package. A class that inherits the Collection interface can throw this exception to show that an inherited method is not supported in that class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.163.197