Computer Programming FINAL Exam preparation

Ace your homework & exams now with Quizwiz!

What is the output of the following code? public class Inherit { abstract class Figure { void display() { System.out.println("Figure"); } } abstract class Rectangle extends Figure { } class Box extends Rectangle { void display() { System.out.println("Rectangle"); } } Inherit() { Figure f = (Figure) new Box(); f.display(); Rectangle r = (Rectangle) f; r.display(); } public static void main(String[] args) { new Inherit(); } } a. Rectangle Rectange b. Rectangle Figure c. Figure Rectangle d.Figure Figure e. None of these

ANS: A f is a polymorphic reference variable, as is r. Trace through the inheritance structure to see that both references' invocation of the display() method will, indeed, display Rectangle.

Aside from writing recursive methods, another way that recursion is often used is to define a. words in English b. mathematical functions c. rules and laws d. child classes of a parent class in object-oriented programming e. recursion is used in all of these

ANS: B Mathematics often defines functions recursively for simplicity.

Although insertion sort and selection sort have generally the same performance, the selection sort has an advantage over the insertion sort. What is this advantage? a. The selection sort usually makes fewer comparisons. b. The selection sort usually makes fewer swaps. c. The selection sort usually makes fewer passes. d. The selection sort usually makes fewer selections. e. None of these

ANS: B The selection sort may make fewer swaps because at each stage of the process, elements are moved into their final positions and never are moved again.

Character streams manage a. byte-sized data b. binary data c. Unicode characters d. ASCII characters e. compressed data

ANS: C Character streams are used to manage 16-bit Unicode characters. This differs from a byte stream that is used to manage any kind of byte-sized data, including ASCII characters and binary data of other types.

Given the following recursive method: public int question1_2(int x, int y) { if (x == y) return 0; else return question1_2(x-1, y) + 1; } If the method is called as question1_2(8, 3), what is returned? a. 11 b. 8 c. 5 d. 3 e. 24

ANS: C The method computes x - y if x > y. The method works as follows: each time the method is called recursively, it subtracts 1 from x until (x == y) is becomes true, and adds 1 to the return value. So, 1 is added each time the method is called, and the method is called once for each int value between x and y.

A Java program can handle an exception in several different ways. Which of the following is not a way a Java program might handle an exception? a.ignore the exception b. handle the exception where it arises using try and catch statements c. propagate the exception to another method where it can be handled d. throw the exception to a predefined Exception class to be handled e. All of these are valid ways to handle an exception

ANS: D A thrown exception is either caught by the current code if the code is contained inside a try statement and the appropriate catch statement is implemented, or else it is propagated to the method that invoked the method that caused the exception. Then it is caught there in an appropriate catch statement, or else it continues to be propagated through the methods in the opposite order that those methods were invoked. This process stops however once the main method is reached. If not caught there, the exception causes termination of the program (this would be answer A, the exception was ignored). However, an exception is not thrown to an Exception class.

Which of the following is true about a comparison between the selection sort and the insertion sort? a. The selection sort requires more additional memory than the insertion sort. b. The insertion sort requires more additional memory than the selection sort. c. Both methods require approximately the same amount of additional memory as the data they are sorting. d. Neither method requires additional memory. e. None of these

ANS: D Both the selection sort and the insertion sort can be implemented "in place." This means that no additional memory is required. The data being sorted is just rearranged within the data array as either sort progresses.

True/False: If an exception is thrown and not caught anywhere in the program, then the program terminates.

ANS: T Exceptions are events of interest or are run-time situations that cannot be handled normally without an exception handler. An exception is caught by an associated exception handler. If the exception is thrown but not handled, then the program must terminate.

4 visibility modifiers:

default public protected private

Which statement below is not true? A. Event-driven programming pre-determines computation order B. Event-driven programming let users or environment specify the computation order C. Graphic user interfaces are based on event-driven programming D. Keyboard key strikes and mouse movement are examples of events

A

Abstract methods are used when defining a. interface classes b. derived classes c. classes that have no constructor d. Arrays e. classes that have no methods

ANS: A An interface is a class that has defined some of its components, but leaves other components (methods) for you to implement. So, these components (methods) are referred to as abstract and defined in the interface class as abstract.

Assume that Student, Employee and Retired are all extended classes of Person, and all four classes have different implementations of the method getMoney. Consider the following code where ... indicates the required parameters for the constructors: Person p = new Person(...); int m1 = p.getMoney(); // assignment 1 p = new Student(...); int m2 = p.getMoney(); // assignment 2 if (m2 < 100000) p = new Employee(...); else if (m1 > 50000) p = new Retired(...); int m3 = p.getMoney(); // assignment 3 The reference to getMoney() in assignment 1 is to the class a. Person b. Student c. Employee d. Retired e. This cannot be determined by examining the code

ANS: A At this point of the program, p is a Person, and so getMoney is a reference to Person's getMoney method.

Assume Exceptionname is a checked exception. If a method uses a class that can generate Exceptionname, then either the method must include try and catch statements where a catch statement catches Exceptionname, or the method header must include the statement a. throw Exceptionname b. throws Exceptionname c. catch Exceptionname d. catches Exceptionname e. implements Exceptionname

ANS: B A checked exception must be caught somewhere and so, if not caught in the method that might generate the exception, the exception must be thrown to whatever called the method. This is accomplished by stating that the method throws Exceptionname.

Which of the following is not a method of the Object class? a. clone b. compareTo c. Equals d. toString e. All of the above are methods of the Object class

ANS: B The Object class defines clone to create a copy of any object, equals to determine if two objects are the same object, and toString to translate an Object into a String. However, compareTo is not implemented by Object and must be explicitly implemented in any class that wants to implement the Comparable interface.

An exception can produce a "call stack trace" which lists a. the active methods in the order that they were invoked b. the active methods in the opposite order that they were invoked c. the values of all instance data of the object where the exception was raised d. the values of all instance data of the object where the exception was raised and all local variables and parameters of the method where the exception was raised e. the name of the exception thrown

ANS: B The call stack trace provides the names of the methods as stored on the run-time stack. The method names are removed from the stack in the opposite order that they were placed; that is, the earliest method is placed there first, the next method second, and so forth so that the most recently invoked method is the last item on the stack. Thus, it is the first one removed. The stack trace then displays all active methods in the opposite order that they were called (most recent first).

Inheritance through an extended (derived) class supports which of the following concepts? a. Interfaces b. Modulary c. information hiding d. code reuse e. Correctness

ANS: D By extending a class and inheriting from it, the new class does not have to reimplement any of those inherited methods or instance data, thus saving the programmer time and effort. So, code reuse is the ability to reuse someone else's code for your benefit by extending it for your needs.

Given the following recursive method: public int question1_2(int x, int y) { if (x == y) return 0; else return question1_2(x-1, y) + 1; } Calling this method will result in infinite recursion if which of the following conditions is initially true? a. (x == y) b. (x != y) c. (x > y) d. (x < y) e. (x == 0) && (y != 0)

ANS: D If (x < y) is true initially, then the else clause is executed resulting in the method being recursively invoked with a value of x - 1, or a smaller value of x, so that (x < y) will be true again, and so for each successive recursive call, (x < y) will be true and the base case, x == y, will never be true.

An exception that could also arise in the try statement that does not have an associated catch statement is a. ClassNotFoundException b. IllegalArgumentException c. NegativeArraySizeException d. NullPointerException e. OutOfMemoryException

ANS: D If the array has not yet been instantiated, then it throws a NullPointerException. The ClassNotFoundException, IllegalArgumentException and OutOfMemoryException will not be thrown since there is no code in the try statement that either refers to some unknown class, uses an argument, or deals with the generation of new memory. The NegativeArraySizeException will only arise when instantiating an array.

True/False: Java doesn't support multiple inheritance; but it does support the implementation of multiple interfaces.

ANS: T Single inheritance is one of Java's strong points. One can achieve most of the advantages of multiple inheritance by implementing multiple interfaces.

True/False: The following two methods will both compute the same thing when invoked with the same value of x. That is, method1(x) = = method2(x). public int method1(int x) { if (x > 0) return method1(x - 1) + 1; else return 0; } public int method2(int x) { if (x > 0) return 1 + method2(x - 1); else return 0; }

ANS: T The only difference between the two methods is the order of the recursive call and adding 1 to the return value. The difference is denoted by calling the first method head recursive and the second tail recursive. So both methods will compute the same value, but arrive at the value in different ways.

True/False: A class reference can refer to any object of any class that descends from the class.

ANS: T This is one of the polymorphic functions of using a class name to declare a reference variable.

True/False: A method's parameter can be polymorphic, giving the method flexible control of its arguments.

ANS: T To accomplish this, merely use an interface name or a base class name to declare the variable. Then the parameter is polymorphic, referring to the correct instance of the class during execution, with the correct semantics being accessed during execution.

True/False: A recursive method without a base case leads to infinite recursion.

ANS: T Without the base case, the recursive method calls itself without the ability to stop, and thus leads to infinite recursion.

Given the interface declared below public interface Movable { public void move ( double dx, double dy); } What must we do in order for DrivableClass to implement this interface if is currently declared as public class DrivableClass implements Movable READ all answers. A. The class DrivableClass heading needs to be re-written: public class DrivableClass extends Movable B.The class DrivableClass needs to add a method with signature: public void move (double dx, double dy) C.The class DrivableClass heading needs to be re-written as shown in answer (A) and it needs the method shown in answer (B). D.The class heading for Movable needs to be re-written: public class Movable implements DrivableClass

B

What is the return value of the following method when it is called with func(5)? public int func(int n){ if (n == 0) return 0; else return n + func(n-1); } A. 10 B. 15 C. 0 D. None of above

B

You are given these class definitions: public class Animal { public void makeNoise() {System.out.println("Noise");} } public class Dog extends Animal { public void makeNoise() {System.out.println("Woof");} } What will be the output of the following code? Animal pet2 = new Dog(); pet2.makeNoise(); A. Noise B. Woof C. NoiseWoof D. Nothing because the code will not compile.

B

A singly linked list is implemented with Node objects declared below. class Node { int data; Node next; } What is the function of the following code? int funct(Node head) { if (head == null) return 0; return head.data + funct (head.next); } A. Reverse the list B. Count the nodes in the list C. Sum up the values in the list D. None of the above

C

What is the output by this code? int waitTime = 35; try { System.out.print("Enter "); if (waitTime > 30) throw new Exception("Too Much Time! "); System.out.print("Leaving "); } catch (Exception e) { System.out.print(e.getMessage()); } System.out.print("End"); A. Enter Too Much Time! Leaving End B. Enter Leaving Too Much Time! End C. Enter Too Much Time! End D. EnterLeavingEnd

C

You are given these class definitions: public class Animal { public void makeNoise() {System.out.println("Noise");} } public class Dog extends Animal { public void makeNoise() {System.out.println("Woof");} } Which of the following statements will compile? (1) Animal pet1 = new Animal(); (2) Animal pet1 = new Dog(); (3) Dog pet1 = new Dog(); (4) Dog pet1 = new Animal(); A. All four will compile. B. (1) and (3) will compile, but (2) and (4) will not. C. (1), (2) and (3) will compile, but not (4). D. (1), (3) and (4) will compile, but not (2).

C

Consider the following class definition: public class AClass { private int x, y; public AClass(int a, int b) { x = a; y = b; } //other methods } and this class definition public class BClass extends AClass { private int z; Which of the following would best define the BClass constructor? A. public BClass(int a, int b, int c) { super(a, b, c); } B. public BClass(int a, int b, int c) { x = a; y = b; z = c; } C. public BClass(int a, int b, int c) { z = c; } D. public BClass(int a, int b, int c) { super(a, b); z = c; }

D

The difference between direct and indirect recursion is a. direct recursion occurs when a method invokes itself; indirect recursion occurs when there is an intervening method b. indirect recursion occurs when a method invokes itself; direct recursion occurs when there is an intervening method c. direct recursion only occurs with methods declared to be private; indirect recursion can occur with methods declared to be private, protected, or public d. indirect recursion only occurs with methods declared to be private; direct recursion can occur with methods declared to be private, protected, or public e. None of these

ANS: A Direct recursion means that a method directly invokes itself with no intervening method. Indirect recursion occurs when there are one or more intervening methods before the original method is invoked again.

What are the main programming mechanisms that constitute object-oriented programming? a. encapsulation, inheritance, polymorphism b. encapsulation, abstraction, inheritance c. inheritance, polymorphism, recursion d. polymorphism, recursion, abstaction e. None of these

ANS: A Encapsulation is the isolation of portions of code so that they cannot be accidentally modified; inheritance provides for code reuse; polymorphism provides for one-name, many semantics. Abstraction is a useful attribute, but it is not a mechanism. Recursion is a control structure, providing for a different way to express looping or repetition.

Which of the following is true about Java classes? a. All classes must have one parent but may have any number of children (derived or extended). b. All classes must have one parent and may have a single child (derived or extended) but may have any number of parent classes. c. All classes can have any number (zero or more) of parent classes and any number of children (derived or extended) classes. d. All classes must have one parent and may have a single child (derived or extended) class. e. All classes can have either zero or one parent class and any number of child (derived or extended) classes.

ANS: A Java supports inheritance but not multiple inheritance, so a Java class can have any number of children but only one parent. Further, since all Java classes inherit either directly or indirectly from the Object class, all Java classes have exactly 1 parent class.

The Koch fractal of order 1 is a. a triangle b. a square c. a point d. a circle e. None of these

ANS: A The Koch fractal of order 1 is the simplest possible closed figure that contains an area--a triangle.

Which of the following is not true of the RuntimeException class? a. All RuntimeException throw checked exceptions. b. All RuntimeException are Throwable objects. c. RuntimeException has child classes ArithmeticException and NullPointerException. d. RuntimeException objects are not Error objects. e. All of these are true

ANS: A The answers in B, C and D are all true, RuntimeException are Throwable objects and are not part of the Error class, and two types of RuntimeException are ArithmeticException and NullPointerException. Exceptions that are not RuntimeExceptions include various checked exceptions, but RuntimeExceptions are not checked exceptions.

What kind of performance can you expect if you perform a linear search on a sorted array? a. The performance will be about the same as on an unsorted array. b. The performance will be much better than on an unsorted array. c. The performance will be much worse than on an unsorted array. d. The performance will be worse by about n^2 in this case e. None of these

ANS: A The linear search doesn't make any assumptions about whether or not its data is sorted. So, if the data happens to be sorted or not, it won't make any difference. The linear sort will perform roughly as n.

In order to have some code throw an exception, which of the following reserved words should you use? a. throw b. throws c. try d. Throwable e. goto

ANS: A The reserved word throw is used to throw an exception when the exception is detected, as in: if (score < 0) throw new IllegalTestScoreException("Input score " + score + " is negative");

Which of the following is correct? a. a base class is a parent class or super class b. a base class is a child class or derived class c. a child class is a super class of its parent d. a parent class is a subclass of its child e. None of these are correct

ANS: A The terms base class, parent class, and super class are synonyms for one another. They all imply that the class will be used as a base for inheritance, and that subsequent classes will extend (inherit from) the base class.

Aside from permitting inheritance, the visibility modifier protected is also used to a. permit access to the protected item by any class defined in the same package b. permit access to the protected item by any static class c. permit access to the protected item by any parent class d. ensure that the class cannot throw a NullPointException e. define abstract elements of an interface

ANS: A The visibility modifier protected is used to control access to the item in a protected (guarded) manner. The protection is that access is restricted to the current class (like private items), classes in the same package, or extended classes of this class.

Which of the following methods will sort an array of floats in ascending order (по возрастанию)? a. void arrange(float[] ary) { for (int n = 0; n < ary.length; n++) for (int k = n; k < ary.length; k++) if (ary[n] > ary[k]) { float x = ary[n]; ary[n] = ary[k]; ary[k] = x; } } b. void arrange(float[] ary) { for (int n = 0; n < ary.length; n++) for (int k = n; k < ary.length; k++) if (ary[n] < ary[k]) { float x = ary[n]; ary[n] = ary[k]; ary[k] = x; } } c. void arrange(float[] ary) { for (int n = 1; n <= ary.length; n++) for (int k = n; k < ary.length; k++) if (ary[n] > ary[k]) { float x = ary[n]; ary[n] = ary[k]; ary[k] = x; } } d. void arrange(float[] ary) { for (int n = 0; n < ary.length; n++) for (int k = n; k < ary.length; k++) if (ary[n] > ary[k]) float x = ary[n]; ary[n] = ary[k]; ary[k] = x; } e. None of these

ANS: A This code sorts correctly. The other alternatives are missing braces, have incorrect comparisons, or incorrect limits on their loops.

What is the output of the following code? (Consider the polymorphic invocation.) public class Inherit { class Figure { void display() { System.out.println("Figure"); } } class Rectangle extends Figure { void display() { System.out.println("Rectangle"); } } class Box extends Figure { void display() { System.out.println("Box"); } } Inherit() { Figure f = new Figure(); Rectangle r = new Rectangle(); Box b = new Box(); f.display(); f = r; f.display(); f = b; f.display(); } public static void main(String[] args) { new Inherit(); } } a. Figure Rectangle Box b. Rectangle Box c. Figure Figure Figure d. Syntax error. This code won't compile or execute e. None of these

ANS: A This is a perfect example of polymorphism. The first invocation of the display method has a Figure as its referent. In the second invocation, the reference has been changed to Rectangle. Then for the third invocation it has been changed to Box.

Can a program exhibit polymorphism if it only implements early binding? a. Yes, because one form of polymorphism is overloading. b. No, because without late binding, polymorphism cannot be supported. c. Yes, because as long as the program uses inheritance and/or interfaces, it supports polymorphism. d. Yes, because early binding has nothing to do with polymorphism. e. None of these

ANS: A While inheritance and interfaces support polymorphism, they only do so if one has late binding. But overloading is a form of polymorphism--one (method) name, multiple bodies--so as long as the program uses overloading, polymorphism is in use.

If a programmer writes a class that he wants to be extended by another programmer, then this programmer must a. change private methods and instance data to be protected b. change public methods and instance data to be protected c. change all the methods to be protected d. change the class to be protected e. None of these; the programmer doesn't have to change anything

ANS: A protected items are accessible by any subclass of the class that defines them while private items cannot be accessed by any other class. Therefore, previously defined private items must now be protected. Previously defined public entities should remain public so that all other classes can still access those public entities. Previously defined private items should not be made public because this would allow all classes to access them rather than just child classes.

What does the following recursive method determine?. public boolean question16(int[]a, int[] b, int j) { if (j == a.length) return false; else if (j == b.length) return true; else return question16(a, b, j+1); } a. returns true if a and b are equal in size, false otherwise b. returns true if a is larger than b, false otherwise c. returns true if b is larger than a, false otherwise d. returns true if a and b have no elements e. return the length of array a + length of array b

ANS: B The method returns true if the third parameter, j, is equal to the length of b but not equal to the length of a. Thus, the method returns true if the third parameter has reached the value indicating the end of array b but not the end of array a so this is true if a is larger than b. If a and b are equal length or if a is shorter than b, false is returned.

A processing stream is a data stream that a. can manage both input streams and output streams at the same time b. performs some manipulation or process on the data c. can only manage input streams d. operates on input and output devices but not files e. can manage byte streams and character streams at the same time

ANS: B A data stream represents a particular source or destination stream and is used for input or output. A processing stream is like a data stream where some additional process(es) is(are) added to the input or output. For example, a processing byte stream might input all items from a file and remove any ASCII characters that are not digits so that an input expected to be a number will not throw a NumberFormatException.

What is a fractal? a. a portion of a larger structure (a fraction) b. a geometric shape that can be made up of the same pattern repeated at different scales and orientations c. a recursively defined numeric function d. a ratio (a fraction) e. None of these

ANS: B A fractal is a geometric shape that is "self-similar"; that is, it appears to be the same regardless of scale and orientation. The same shape appears at different scales and orientations.

Assume that Student, Employee and Retired are all extended classes of Person, and all four classes have different implementations of the method getMoney. Consider the following code where ... indicates the required parameters for the constructors: Person p = new Person(...); int m1 = p.getMoney(); // assignment 1 p = new Student(...); int m2 = p.getMoney(); // assignment 2 if (m2 < 100000) p = new Employee(...); else if (m1 > 50000) p = new Retired(...); int m3 = p.getMoney(); // assignment 3 The reference to getMoney() in assignment 2 is to the class a. Person b. Student c. Employee d. Retired e. This cannot be determined by examining the code

ANS: B At this point of the program, p is a Student, and so getMoney is a reference to Student's getMoney method.

What can be said about the difference or similarity, if any, between an infinite loop and an infinite recursion? a. It is impossible to detect the latter while it's easy to detect the former. b. Both continue to repeat indefinitely. c. Both will be caught by the compiler. d. Both will be caught by the Java Virtual Machine during execution. e. None of these

ANS: B Both infinite loops and recursion are similar in that they continue to repeat indefinitely. Neither can be caught by the compiler or by the JVM.

A method that uses the Scanner class to obtain input does not require either catching or throwing an IOException. This is because a. the Scanner class does not call upon any classes that throw checked exceptions b. the Scanner class's methods call input methods in try statements and catch IOExceptions so that they are handled directly in the Scanner class c. the Scanner class uses dialog boxes instead of java.io classes so that it does not have to deal with IOExceptions d. the Scanner class overrides the class IOException making it an unchecked exception e. None of the above; methods do require handling IOExceptions even if thrown by a method in a Scanner class

ANS: B By having its own catch (IOException) catch statement, any code in the Scanner class that causes an IOException is caught by the Scanner class so that classes that might use the Scanner class do not have to handle this checked exception.

What is the output of the following code? public class Inherit { abstract class Speaker { abstract public void speak(); } class Cat extends Speaker { public void speak() { System.out.println("Woof!"); } } class Dog extends Speaker { public void speak() { System.out.println("Meow!"); } } Inherit() { Speaker d = new Dog(); Speaker c = new Cat(); d.speak(); c.speak(); } public static void main(String[] args) { new Inherit(); } } a. Woof! Meow! b. Meow! Woof! c. Meow! Meow! d.Woof! Woof! e.None of these

ANS: B Carefully watch the assignment of objects to the polymorphic references variables, d and c. Then check to see what Cat and Dog objects actually "speak."

Polymorphism is achieved by a. overloading b. overriding c. embedding d. abstraction e. encapsulation

ANS: B Overloading just provides alternatives for methods with differing parameter lists. Overriding provides for polymorphism, because the appropriate method is invoked depending upon the object that currently is being referenced. Embedding is the enclosing of classes within classes. Abstraction has nothing to do with polymorphism. Encapsulation is achieved using the visibility modifiers.

Java does not support multiple inheritance but some of the abilities of multiple inheritance are available by a. importing classes b. implementing interfaces c. overriding parent class methods d. creating aliases e. using public rather than protected or private modifiers

ANS: B Since a class can implement any number of interfaces, that class is in essence using the interface classes as if those interfaces were defined in this class. So this class is inheriting the methods and constants of the interfaces. Further, the class could extend another class and thus inherit directly and indirectly from multiple classes. This is not the exact same as multiple inheritance, but it is as close as Java comes to that concept.

public class AClass { protected int x; protected int y; public AClass(int a, int b) { x = a; y = b; } public int addEm() { return x + y; } public void changeEm() { x++; y--; } public String toString() { return "" + x + " " + y; } } You want addEm to now add all three values, return the sum, and changeEm to change x and y, but leave z alone. Which should you do? a. Redefine addEm and changeEm without referencing super.addEm() or super.changeEm(). b. Redefine addEm to return the value of z+super.addEm(), but leave changeEm alone. c. Redefine changeEm to call super.changeEm() and then set z = x + y, but leave addEm alone. d. Redefine addEm to return the value of z+super.addEm() and redefine changeEm to call super.changeEm() and then set z = x + y. e. Redefine changeEm to call super.changeEm() without doing anything to z, and redefine addEm to return super.addEm().

ANS: B Since super.changeEm() will not affect z and we don't want changeEm()to affect z, there is no need to redefine changeEm()for BClass. Any reference to changeEm()will reference AClass's version which is the same one that BClass will use. But addEm needs redefining because the inherited method addEm calls AClass's addEm which only adds x and y together. Now, we want to add x, y and z together. We can either redefine addEm enntirely, or use super.addEm()and add z to the value returned. The latter approach is better since it reuses previously written code.

Which of the following messages passed to the String str could throw a StringIndexOutOfBoundsException? a. str length(); b. str charAt(2); c. str replace('a', 'A'); d. str equals(str); e. Any of these could throw a StringIndexOutOfBoundsException

ANS: B The StringIndexOutOfBoundsException is thrown if a parameter of a String method references a position in the String that is beyond the bounds of the String (i.e. a negative int or an int greater than or equal to the number of characters in the String). This can occur in either charAt or substring methods.

What is wrong with the following recursive sum method? The method is supposed to sum up the values between 1 and x (for instance, sum(5) should be 5 + 4 + 3 + 2 + 1 = 15). public int sum(int x) { if (x == 0) return 0; else return sum(x - 1) + x; } a. The base case should return 1 instead of 0. b. The recursive case should return sum(x - 1) + 1 instead of sum(x - 1) + x. c.The base case condition should be (x <= 0) instead of (x == 0). d. The recursive case should return sum(x) + 1. e. The method should return a boolean instead of an int.

ANS: B The method does not appropriately handle a negative parameter, such as sum(-5). The result is infinite recursion. We might define a negative parameter as something that should return 0, or allow a negative parameter to compute a negative sum as in: public int sum(int x) { if (x == 0) return 0; else if (x < 0) return -1 * sum(-x); else return sum(x - 1) + x; }

Given the following partial class definition: public class A1 { public int x; private int y; protected int z; ... } public class A2 extends A1 { protected int a; private int b; ... } public class A3 extends A2 { private int q; ... } Which of the following is true with respect to A1, A2, and A3? a. A1 is a subclass of A2 and A2 is a subclass of A3 b. A3 is a subclass of A2 and A2 is a subclass of A1 c. A1 and A2 are both subclasses of A3 d. A2 and A3 are both subclasses of A1 e. A1, A2 and A3 are all subclasses of the class A

ANS: B The reserved word extends is used to create a subclass. Since A2 extends A1, A2 is a subclass of A1. Since A3 extends A2, A3 is a subclass of A2.

The relationship between a parent class and a child class is referred to as a(n) __________ relationship. a. has-a b. is-a c. was-a d. instance-of e. Alias

ANS: B The term "is-a" is used to express that a subclass is a type of parent class. For instance, a graduate student is a type of student. The subclass is a more specific type. The has-a relationship refers to the attributes or elements of a class (for instance, a student has a GPA) and instance-of refers to the relationship between a class and an instantiated object of that class. There is no such thing as a was-a relationship and an alias denotes two variables that reference the same object or instance.

An int array stores the following values: 9, 4, 12, 2, 6, 8, 18. Which of the following lists of numbers would accurately show the array after the second pass of the selection sort algorithm? a. 9, 4, 12, 2, 6, 8, 18 b. 2, 4, 9, 6, 12, 8, 18 c. 2, 4, 12, 9, 6, 8, 18 d. 2, 4, 6, 8, 9, 12, 18 e. 2, 4, 9, 12, 6, 8, 18

ANS: C After one pass, the array would be 2, 4, 12, 9, 6, 8, 18. The second pass would look to swap the item in array index 1 (4) with the smallest value after 2 (4). So, 4 would swap with 4 and the array would stay the same as it was after the first pass.

Given the following partial class definition: public class A1 { public int x; private int y; protected int z; ... } public class A2 extends A1 { protected int a; private int b; ... } public class A3 extends A2 { private int q; ... } Which of the following is true regarding the use of instance data y of class A1? a. It is accessible in A1, A2, and A3 b. It is accessible in A1 and A2 c. It is accessible only in A1 d. It is accessible only in A3 e. It is accessible to any of the three classes

ANS: C Because it is declared as a private instance data, it is not inherited by any subclasses, and therefore y is only accessible in the class it was defined, A1.

NullPointerExceptions and ArithmeticExceptions are both derived from which class? a. Error b. Exception c. RuntimeException d. IllegalAccessException e. CheckedException

ANS: C Both of these exceptions are children of the RuntimeException class which, itself, is a child of Exception. Error is a throwable object that is different from Exception while IllegalAccessException and CheckedException are children of Exception but not of RuntimeException.

Both the insertion sort and the selection sort algorithms have efficiencies on the order of ________ where n is the number of values in the array being sorted. a. n b. n * log n c. n^2 d. n^3 e. the insertion sort has an efficiency of n and the selection sort has an efficiency of n^2

ANS: C Both sorting algorithms use two nested loops which both execute approximately n times apiece, giving a complexity of n * n or n^2 for both.

Given the following partial class definition: public class A1 { public int x; private int y; protected int z; ... } public class A2 extends A1 { protected int a; private int b; ... } public class A3 extends A2 { private int q; ... } Which of the following lists of instance data are accessible in class A2? a. x, y, z, a, b b. x, y, z, a c. x, z, a, b d. z, a, b e. a, b

ANS: C Class A2 has access to all of its own instance data (a, b) and any instance data from A1 that were protected (z). Further, all classes, including A2, have access to A1's x since it is public, so x, z, a, b are accessible in A2.

Each time the order of a Koch fractal increases by one, the number of straight line segments a. increases by a factor of two b. increases by a factor of three c. increases by a factor of four d. is squared e. is cubed

ANS: C Each line segment is replaced by four equal-length line segments each time the order increases by one. So, the total number of straight line segments increases by a factor of four each time the order is increased by one.

Which of the following is an example of multiple inheritance? a. a computer can be a mainframe or a PC b. a PC can be a desktop or a laptop c. a laptop is both a PC and a portable device d. a portable device is a lightweight device e. Macintosh and IBM PC are both types of PCs

ANS: C Multiple inheritance means that a given class inherits from more than one parent class. Of those listed above, a laptop computer inherits properties from both PCs and portable devices. The answers in A, B and E are all examples of single inheritance where a class has at least two children (in A, computer has children mainframe and PC, in B, PC has children desktop and laptop, in E, PC has children Macintosh and IBM PC).

An int array stores the following values: 9, 4, 12, 2, 6, 8, 18. Which of the following lists of numbers would accurately show the array after the first pass of the selection sort algorithm? a. 9, 4, 12, 2, 6, 8, 18 b. 2, 4, 9, 6, 12, 8, 18 c. 2, 4, 12, 9, 6, 8, 18 d. 2, 4, 6, 8, 9, 12, 18 e. 2, 4, 9, 12, 6, 8, 18

ANS: C On each successive pass of selection sort, the smallest of the unsorted values is found and swapped with the current array index (where the current index starts at 0 and goes until the second to last position in the array). On the first pass, the smallest element, 2, is swapped with index 0, so 2 and 9 swap places.

public class AClass { protected int x; protected int y; public AClass(int a, int b) { x = a; y = b; } public int addEm() { return x + y; } public void changeEm() { x++; y--; } public String toString() { return "" + x + " " + y; } } Which of the following would best redefine the toString method for BClass? a. public String toString(int z) { return " " + x + " " + y + " " + z; } b. public String toString() { return super.toString(); } c. public String toString() { return super.toString() + " " + z; } d. public String toString() { return super.toString()+" " x+" "+y+" "+z; } e. public String toString() { return " " + x + " + y + " " + z; }

ANS: C The best way to redefine a method is to reuse the parent class's method and supplement it with the code needed to handle the changes in the subclass. Answer C does this. Answer E accomplishes the same task, but does not reuse any of the parent class's code. Answer B returns only x and y, not z, and answer D returns x, y, and z, while answer A is syntactically invalid because the toString method does not accept a parameter.

What does the following method compute? Assume the method is called initially with i = 0. public int question9(String a, char b, int i) { if (i == a.length()) return 0; else if (b == a.charAt(i)) return question9(a, b, i+1) + 1; else return question9(a, b, i+1); } a. the length of String a b. the length of String a concatenated with char b c. the number of times char b appears in String a d. the value 1 if char b appears in String a at least once and 0 otherwise e. the char which appears at location i in String a

ANS: C The method compares each character in String a with char b until i reaches the length of String a. 1 is added to the return value for each match.

public static void main(String[] args) { try { ExceptionThrowerCode etc = new ExceptionThrowerCode(); etc.m1(); etc.m2(); } catch (ArithmeticException ae) { ... } } public class ExceptionThrowerCode { ... public void m1() { ... } public void m2() { try { m3(); } catch(ArithmeticException ae) {...} catch(NullPointerException npe) {...} } public void m3() { try { ... } catch(ArithmeticException ae) {...} }} If a NullPointerException arises in the try statement in m3 a. it is caught in main b. it is caught in m1 c. it is caught in m2 d. it is caught in m3 e. it is not caught and the program terminates

ANS: C The method m3 has no catch statement for a NullPointerException, and so the exception is propagated to the calling method, m2. Method m2 has a catch statement for a NullPointerException so that is where the exception is caught.

The following method should return true if the int parameter is even and either positive or 0, and false otherwise. Which set of code should you use to replace ... so that the method works appropriately? public boolean question3(int x) { ... } a. if (x == 0) return true; else if (x < 0) return false; else return question3(x - 1); b. if (x == 0) return false; else if (x < 0) return true; else return question3(x - 1); c. if (x == 0) return true; else if (x < 0) return false; else return question3(x - 2); d. if (x == 0) return false; else if (x < 0) return true; else return question3(x - 2); e. return(x == 0);

ANS: C The method will recursively call itself subtracting 2 from x until x == 0 or x<0. If x == 0, then x - 2 * i == 0 (for some int value i) or x == 2 * i, so x must be even. Otherwise, the recursion ends when x < 0, meaning that the original x was odd or less than 0.

Why is the following method one which has infinite recursion? public int infiniteRecursion(int n) { if (n > 0) return infiniteRecursion(n) + 1; else return 0; } a. because there is no base case b. because the base case will never be true c. because the recursive call does not move the parameter closer to the base case d. because the recursive call moves the problem further away from the base case e. None of these; this method isn't infinitely recursive

ANS: C The recursive case has the method calling itself with the same parameter, and so n does not change, thus if (n > 0) is initially true, it will remain true.

System.err is a(n) a. input stream b. GUI dialog box that indicates when an error has arisen c. object d. Error subclass e. RuntimException subclass

ANS: C There are three default streams available in Java: System.in, System.out, and System.err. All of these are objects with System.in being an input stream, System.out being an output stream and System.err being an error stream (which is also an output stream).

A recursive algorithm is superior (превосходит) to an iterative algorithm along which of the following criteria? a. The recursive algorithm is easier to debug. b. The recursive algorithm is computationally more efficient. c. The recursive algorithm is more elegant. d. The recursive algorithm requires less memory to execute. e. All of these

ANS: C When comparing most recursive algorithms to their iterative counterparts, it is almost always the case that the recursive algorithm is shorter, so it tackles the same problem with less code. This means it is more elegant (which does not necessarily mean it is easier to understand or more efficient).

The difference between a checked and an unchecked exception is a. checked exceptions need not be listed in a throws clause b. unchecked exceptions must be listed in a throws clause c. neither kind of exception follows the rules of exception propagation d. an unchecked exception requires no throws clause e. a checked exception always must be caught by a try block while this is not true for an unchecked exception

ANS: D A checked exception must either be caught or it must be listed in a throws clause. An unchecked exception requires no throws clause. Both kinds of exceptions follow the rules of exception propagation.

public class AClass { protected int x; protected int y; public AClass(int a, int b) { x = a; y = b; } public int addEm() { return x + y; } public void changeEm() { x++; y--; } public String toString() { return "" + x + " " + y; } } You want to extend AClass to BClass. BClass will have a third int instance data, z. Which of the following would best define BClass's constructor? a. public BClass(int a, int b, int c) { super(a, b, c); } b. public BClass(int a, int b, int c) { x = a; y = b; z = c; } c. public BClass(int a, int b, int c) { z = c; } d. public BClass(int a, int b, int c) { super(a, b); z = c; } e. public BClass(int a, int b, int c) { super(); }

ANS: D Inheritance is useful because it allows you to reuse code. For this problem, you would want to reuse as much of AClass as possible. Answer D allows you to use AClass's constructor, which expects two int parameters. This sets x and y to be a and b respectively. But since AClass does not have an instance data z, you need to directly assign z to be c in the constructor. The answer in B will also work, but does not reuse any code and so is not as desirable as D. The answers in A and E are syntactically invalid since they do not pass the correct number of parameters to AClass's constructor. Finally, the answer in C only sets z correctly and leaves x and y uninitialized.

Given the following partial class definition: public class A1 { public int x; private int y; protected int z; ... } public class A2 extends A1 { protected int a; private int b; ... } public class A3 extends A2 { private int q; ... } Which of the following lists of instance data are accessible in class A3? a. x, y, z, a, b, q b. a, b, q c. a, q d. x, z, a, q e. x, a, q

ANS: D Obviously q is accessible in A3. Also, A3 has access to anything inherited from A2, which is a. Additionally, since A2 inherits z from A1, it is also inherited by A3. Finally, since x is public, it is visible to all classes.

public static void main(String[] args) { try { ExceptionThrowerCode etc = new ExceptionThrowerCode(); etc.m1(); etc.m2(); } catch (ArithmeticException ae) { ... } } public class ExceptionThrowerCode { ... public void m1() { ... } public void m2() { try { m3(); } catch(ArithmeticException ae) {...} catch(NullPointerException npe) {...} } public void m3() { try { ... } catch(ArithmeticException ae) {...} }} If an ArithmeticException arises in the try statement in m3 a. it is caught in main b. it is caught in m1 c. it is caught in m2 d. it is caught in m3 e. it is not caught and the program terminates

ANS: D The method m3 has a catch statement for an ArithmeticException, so if one arises in the try statement in m3, it is caught in the catch statement in m3.

Define the magnitude of a number as the location of the decimal point from the left of the number (that is, if a number has 4 digits followed by the decimal point, it will have a magnitude of 4). 100 would then have a magnitude of 3 and 55,555.555 would have a magnitude of 5. A partial recursive method is given below to compute a positive int parameter's magnitude. Which answer below is needed to complete the method? public int magnitude(double x) { if (x < 1) return 0; else return _______; } a. magnitude(x - 1) + 10; b. magnitude(x - 10) + 1; c. magnitude(x / 10) + 10; d. magnitude(x / 10) + 1; e. magnitude(x / 10) * 2;

ANS: D The method must count the number of digits to the left of the decimal point, so it continually divides the value by 10 until the value has no digits to the left of the decimal point (this is the case if the value is less than 1). Each time the value is divided by 10, 1 is added to the return value. 55,555.555 will be divided by 10 five times before it becomes less than 1, and thus return 5.

In order to determine the type that a polymorphic variable refers to, the decision is made a. by the programmer at the time the program is written b. by the compiler at compile time c. by the operating system when the program is loaded into memory d. by the Java run-time environment at run time e. by the user at run time

ANS: D The polymorphic variable can take on many different types, but it is not known which type it has taken on until the program is executing. At the time the variable is referenced, then the decision must be made. That decision is made by the run-time environment based on the latest assignment of the variable.

An int array stores the following values: 9, 4, 12, 2, 6, 8, 18. How many passes will it take in total for the selection sort to sort this array? a. 2 b. 4 c. 5 d. 6 e. 7

ANS: D The selection sort uses two for loops where the outer loop iterates through each array index except for the last one. So it makes a total of n - 1 passes where n is the number of items in the array. Since this array has 7 elements, the outer loop iterates 6 times, or requires 6 passes. You might notice that this array is sorted after only 5 passes, but the selection sort algorithm will still make 6 passes (even if the array had been sorted after only 1 pass, it would still make 6 passes!).

What does the following code do? Assume list is an array of int values, temp is some previously initialized int value, and c is an int initialized to 0. for (j = 0; j < list.length; j++) if (list[j] < temp) c++; a. It finds the smallest value and stores it in temp. b. It finds the largest value and stores it in temp. c. It counts the number of elements equal to the smallest value in list. d. It counts the number of elements in list that are less than temp. e. It sorts the values in list to be in ascending order.

ANS: D The statement if (list[j] < temp) c++; compares each element in list to temp and adds one to c only if the element is less than temp, so it counts the number of elements in list less than temp, storing this result in c.

A variable declared to be of one class can later reference an extended class of that class. This variable is known as a. protected b. derivable c. cloneable d. polymorphic e. None of these; a variable declared to be of one class can never reference any other type of class, even an extended class

ANS: D The term polymorphic means that the variable can have many forms. Under ordinary circumstances, Java is strongly defined. This mean a variable, once declared to be of a type, can never change to be of a different type. The exception to this is that polymorphic variables can be any type of derived class (although not at the same time, the variable can change from one type to another).

Which of the following methods would properly compute the value of x % y (x mod y) recursively, assuming that x and y are not negative numbers? a. public int recursiveMod(int x, int y) { if (x < y) return y; else return recursiveMod(x, y - x); } b. public int recursiveMod(int x, int y) { if (x == y) return 0; else return recursiveMod(x - y, y) + 1; } c. public int recursiveMod(int x, int y) { if (x < y) return x; else return recursiveMod(x - y, y) + 1; } d. public int recursiveMod(int x, int y) { if (x < y) return x; else return recursiveMod(x - y, y); } e. public int recursiveMod(int x, int y) { while (x > y) x = x - y; return x; }

ANS: D The value x % y can be computed by continually subtracting y from x until x<y. Then, the result is x. For instance, 7 % 3 = 4 % 3 = 1 % 3 = 1. The code in answers A, B, and C do not compute x % y and answer E computes mod but uses an iterative solution, not a recursive one.

A finally clause will execute (будет выполнено) a. only if the try statement that precedes it does not throw an exception b. only if the try statement that precedes it throws an exception that is caught c. only if the try statement that precedes it throws an exception that is not caught d. only if the try statement that precedes it throws an exception, regardless of whether or not it is caught e. in any circumstance

ANS: E A finally clause, if specified (because it is optional) will execute no matter what happens with respect to the try and catch statements.

A disabled component is a. one that is grayed out b. one that is no longer active c. one that is still visually apparent but no longer functions if clicked d. provides an indication of functionality that is not currently available e. All of these are true

ANS: E Components that are disabled appear grayed out; they are disabled for the moment, but remain visually apparent. They provide an indication of functionality that can/will be enabled at some other point in time.

We compare sorting algorithms by examining a. the number of instructions executed by the sorting algorithm b. the number of instructions in the algorithm itself (its length) c. the types of loops used in the sorting algorithm d. the amount of memory space required by the algorithm e. A and D

ANS: E Different sorting algorithms require a different number of instructions when executing. The selection sort, for instance, usually requires more instructions than the insertion sort. So we compare sorting algorithms by the number of instructions that each takes to execute to sort the array. We might count the maximum number of instructions that a sorting algorithm will execute in the worst case, or the minimum number in the best case, or count on average the number of instructions executed. If two sorting algorithms require roughly the same number of instructions to sort an array, then we might also examine the amount of memory space required.

The term "exception propagation" means a. an exception is caught by the first catch clause b. an exception not caught by the first catch clause is caught by an outer (enclosing) catch clause c. exceptions are caught, sequentially, by catch clauses in the current try block d. exceptions are always caught by the outermost try block e. None of these explain what exception propagation is

ANS: E Exception propagation means that an exception is caught by a matching catch clause at the current try block level, and if none matches, then at the next enclosing try block level, and so forth, until the exception either has been caught by a matching clause or the exception passes out of the main routine and is caught by the Java Virtual Machine.

When a program terminates because a thrown exception is not handled, the program a. starts up again automatically b. opens a dialog box which asks the user whether the program should start again, end, or enter a debugging mode c. saves all output to a disk file named runStackTrace.txt d. opens a dialog box for the user to specify a disk filename and all output is stored to that file e. outputs a message indicating what the exception was and where it was thrown

ANS: E If a thrown exception is not caught anywhere in the program, the program terminates, displaying the contents of the run stack trace. The first item on the run stack trace is the exception that was thrown and where it was thrown (the line number of the method of the class where the exception was raised)

The Scanner class provides an abstraction for input operations by a. using try and catch statements to catch any IOException instead of throwing the Exception elsewhere b. parsing input lines into individual tokens c. performing conversion operations from String to the appropriate type as specified in the Scanner message d. inputting from the standard input stream if create is called using System.in e. All of these

ANS: E Input into a Java program is difficult because it requires a lot of overhead. The Scanner class implements all of that overhead so that the programmer does not have to see it. Thus, Scanner is an abstraction for performing input operations without the details. These details include importing java.io classes, handling IOExceptions in some way, inputting from the standard input stream, dividing the input into individual tokens and converting each token as needed into the requesting form.

All classes in Java are directly or indirectly subclasses of the __________ class. a. Wrapper b. String c. Reference d. This e. Object

ANS: E Java requires that all classes have a parent class. If a class does not extend another class, then it, by default, extends the Object class. So the Object class is the parent or ancestor of every other class in Java.

An int array stores the following values: 9, 4, 12, 2, 6, 8, 18. Which of the following lists of numbers would accurately show the array after the fourth pass of the selection sort algorithm? a. 9, 4, 12, 2, 6, 8, 18 b. 2, 4, 6, 9, 12, 8, 18 c. 2, 4, 6, 8, 9, 12, 18 d. 2, 4, 6, 9, 8, 12, 18 e. 2, 4, 6, 8, 12, 9, 18

ANS: E The array would be sorted as follows: First pass: 2, 4, 12, 9, 6, 8, 18. Second pass: 2, 4, 12, 9, 6, 8, 18. Third pass: 2, 4, 6, 9, 12, 8, 18. Fourth pass: 2, 4, 6, 8, 12, 9, 18

The instruction super(); does which of the following? a. It calls the method super as defined in the current class. b. It calls the method super as defined in the current class's parent class. c. It calls the method super as defined in java.lang. d. It calls the constructor as defined in the current class. e. It calls the constructor as defined in the current class's parent class.

ANS: E The instruction super(); represents an invocation of something in the current class's parent class. Since there is no message but merely super(), it is an invocation of the parent class's constructor.

public static void main(String[] args) { try { ExceptionThrowerCode etc = new ExceptionThrowerCode(); etc.m1(); etc.m2(); } catch (ArithmeticException ae) { ... } } public class ExceptionThrowerCode { ... public void m1() { ... } public void m2() { try { m3(); } catch(ArithmeticException ae) {...} catch(NullPointerException npe) {...} } public void m3() { try { ... } catch(ArithmeticException ae) {...} }} If a NullPointerException arises in the try statement in m1 a. it is caught in main b. it is caught in m1 c. it is caught in m2 d. it is caught in m3 e. it is not caught and the program terminates

ANS: E The method m1 has no catch statements at all, so any exception is propagated to the calling method, main. The method main only has a catch statement for an ArithmeticException so the NullPointerException is not caught and the program terminates.

Two children of the same parent class are known as a. Aliases b. Relatives c. Clones d. Brothers e. Siblings

ANS: E The relationship between two children of the same parent is referred to as siblings (brothers would imply a gender). Clones are copies of the same object and aliases are the same object. Brothers and relatives are not used to define relationships between classes in Java.

Using the reserved word super, one can a. access a parent class's constructor(s) b. access a parent class's methods and instance data c. access a child class's constructor(s) d. access a child class's methods and instance data e. Both A and B are correct

ANS: E The super reserved word provides a mechanism for accessing a parent class's methods and instance data (whether or not they are hidden). In addition, a parent class's constructor(s) may be accessed using super. So the correct answer is the combination of A and B or E.

If you instantiate an abstract class, the class or object you wind up with a. is also an abstract class b. is a normal class c. is an interface d. is a reference to an Object e. you can't instantiate an abstract class

ANS: E You only can instantiate concrete classes, not abstract ones. But you can extend abstract classes as well as interfaces.

True/False: If an exception arises in a catch statement, and the exception is of the type caught by the catch statement, then the catch statement catches the same exception. For instance, if the following catch statement first catches an ArithmeticException and, while executing, throws another ArithmeticException, it is able to catch the second ArithmeticException as well the first. catch (ArithmeticException ex) {...}

ANS: F An exception causes the current statement to stop executing and control transfers outside to the first catch (after the current statement) that can catch the exception. So a catch statement will not catch exceptions that are thrown from inside of itself although a catch statement can have nested additional try and catch statements.

True/False: Interface classes cannot be extended but classes that implement interfaces can be extended.

ANS: F Any class can be extended whether it is an interface, implements an interface, or neither. The only exception to this is if the class is explicitly modified with the word final in which case it cannot be extended.

True/False: If classes C1 and C2 both implement an interface Cint, which has a method whichIsIt, and if C1 c = new C1(); is performed at one point of the program, then a later instruction c.whichIsIt(); will invoke the whichIsIt method defined in C1.

ANS: F Because C1 and C2 implement the same interface, they both implement whichIsIt. The variable c is known as a polymorphic variable, meaning that it can change from being an C1 to a C2. So, the message c.whichIsIt(); may invoke C1's whichIsIt or C2's whichIsIt. There is no way to tell until run-time.

True/False: An ArithmeticException is a checked exception.

ANS: F It inherits from RunTimeException so it is unchecked.

True/False: It is possible to sort an array of int, float, double or String, but not an array of an Object class such as a CD class.

ANS: F It is possible to sort any type of array as long as the type has some mechanism to compare two elements and determine their proper ordering (less than, equal, greater than). So, if the CD class has a compareTo method, then it would be possible to sort them.

True/False: All run-time errors throw exceptions.

ANS: F Java classifies any throwable object as either an error or an exception, and so no run-time error will throw an exception. Run-time errors cause termination of the program. Exceptions can be handled so that the program continues executing (but only if the exception is handled properly).

True/False: Assume that Poodle is a derived class of Dog and that Dog d = new Dog(...) and Poodle p = new Poodle(...) where the ... are the necessary parameters for the two classes. The assignment statement d = p; is legal even though d is not a Poodle.

ANS: F Since Poodle extends Dog, Dog is a wider class (Poodle is more specific, and therefore narrower). An assignment statement can assign a narrower item into a wider variable (since p is narrower, it can be assigned to d).

True/False: Assume that Poodle is a derived class of Dog and that Dog d = new Dog(...) and Poodle p = new Poodle(...) where the ... are the necessary parameters for the two classes. The assignment statement p = d; is legal even though p is not a Dog.

ANS: F Since Poodle extends Dog, Dog is known as a wider class (Poodle is more specific, and therefore narrower). In any assignment statement, it is possible to take a narrower item and assign it into a wider variable, but it is not possible to assign a wider item into a narrower variable. To accomplish this, a cast must be explicitly made. So, the statement p = d; is illegal although the statement p = (Poodle) d; would be legal.

True/False: A derived class has access to all of the methods of the parent class, but only to the protected or public instance data of the parent class.

ANS: F Since methods can also be declared as private, any private methods are not accessible by a derived class. So, derived classes only have access to the protected and public methods and instance data of the parent class.

True/False: The recursive method to solve the Towers of Hanoi is usable only if the parameter for the number of disks is 7 or smaller.

ANS: F The Towers of Hanoi solution can be used for any number of disks as long as it is at least 1 but the size will affect its performance.

True/False: The binary search can be used on unsorted data. It will just perform more slowly.

ANS: F The binary search only works if the data is sorted. The binary search algorithm proceeds by assuming that there is a strict relationship among every pair of data elements, either ascending or descending. Without this order, the binary search will fail to function correctly.

True/False: Consider the following recursive sum method: public int sum(int x) { if (x == 0) return 0; else return sum(x - 1) + 1; } If the base case is replaced with if (x == 1) return 1; the method will still compute the same thing.

ANS: F The original method causes infinite recursion if called with a parameter < 0, but works properly if called with any parameter >= 0. With the new base case, the method now works properly if called with any parameter >= 1 but causes infinite recursion if the parameter < 1. So, sum(0) now differs from what it was previously.

True/False: To swap the 3rd and 4th elements in the int array values, you would do: values[3] = values[4]; values[4] = values[3];

ANS: F This code first copies values[4] into values[3] and then copies values[3] into values[4]. The result is that whatever was stored in values[4] is now stored in both values[3] and values[4]. In order to perform the swap appropriately, you would need a third variable to be used as a temporary storage location, as in int temp = values[3]; values[3] = values[4]; values[4] = temp;

True/False: The type of the reference, not the type of the object, is used to determine which version of a method is invoked in a polymorphic reference.

ANS: F This is backwards. It is the type of the object, not the type of the reference, that determines which method is invoked.

True/False: An unchecked exception is an exception that must either be caught and handled or listed in the throws clause of any method that might throw or propagate it.

ANS: F This is basically the definition of a checked, not an unchecked exception. Unchecked exceptions can be ignored completely in the code, if desired.

True/False: A is a derived class of X.

ANS: F While A is a descendant of class X, it is not a derived class. Instead, X is a derived class of Y and Y is a derived class of X. A ultimately inherits items from X as long as those items were not overridden by Y.

True/False: Y is a derived class of Z.

ANS: F Y and Z are known as siblings because they are children of the same parent, but Y and Z may have nothing in common other than what they both inherit from X.

True/False: The reserved word, extends, is used to denote a has-a relationship.

ANS: F extends is used for inheritance. Inheritance is an is-a relationship, not a has-a relationship.

True/False: You may use the super reserved word to access a parent class's private members.

ANS: F super will allow access to all non-private members of a parent class but, not to the private ones.

True/False: The following method lacks a base case public int noBaseCase(int x) { if (x > 0) return noBaseCase(x - 1) + 1; else return noBaseCase(x - 2) + 2; }

ANS: T A base case is a condition that, when taken, stops the recursion by not calling the method recursively. In the above method, there is a condition, but whether the condition is true or false, the method invokes itself recursively.

True/False: If class AParentClass has a protected instance data x, and AChildClass is a derived class of AParentClass, then AChildClass can access x but cannot redefine x to be a different type.

ANS: T A derived class can redefine any of the instance data or methods of the parent class. The parent class's version is now hidden, but can be accessed through the use of super, as in super.x.

True/False: A try statement must have at least one catch statements but could have many catch statements and may or may not have a finally clause.

ANS: T All try statements must have at least one catch statement or there is no reason to have the try statement. There can be one catch statement for each type of exception that might be thrown. The programmer may specify as many catch statements as is felt necessary. Further, a try statement may have a finally clause, but does not need one.

True/False: If A, B, Y and Z all contain the same instance data d1, then d1 should be declared in X and inherited into Y, Z, A and B.

ANS: T Anything in common between A, B, Y and Z should be declared in X to properly identify that it is a class trait common amongst them. That is, common elements should be defined as high up in the hierarchy as possible. If all descendants of X have the trait (instance data) d1, then it is part of X too.

True/False: It always is possible to replace a recursion by an iteration and vice versa.

ANS: T Both recursion and iteration are forms of repetition. Whether one phrases the repetition using recursion or iteration is a matter of style, taste, sometimes efficiency, sometimes convenience. But they are equivalent in terms of computation and each may be replaced by the other.

True/False: While the Exception class is part of java.lang, IOException is part of java.io.

ANS: T Exception is the ancestor class of all Exceptions. One child of Exception is IOException, which is a checked exception that is thrown from various IO methods. So, while the Exception class is defined in the java.lang package, the IOException class is defined with the rest of the IO methods, in java.io.

True/False: Java allows one to create polymorphic references using inheritance and using interfaces.

ANS: T Inheritance allows one to use a base variable to refer to various descendent members; the correct one will be used during execution. This is polymorphism in action. Interfaces provide a similar mechanism but use abstract methods rather than the concrete ones used in inheritance. The effect is the same, however.

True/False: An ArithmeticException is Throwable.

ANS: T It inherits Throwable through RunTimeException and Exception.

True/False: Programmers can define their own exceptions by extending the Exception class or one of the descendants of this class.

ANS: T Java predefines a number of Exception classes so that many of the types of exceptions that can cause a program to terminate are handled. However, Java allows programmers to add to the language by defining their own exceptions for whatever unique situations they might encounter. These new exceptions will either be children of the Exception class, or children of subclasses or descendants of Exception.

True/False: One of the advantages of the linear search is that it does not require its data to be sorted.

ANS: T Most other search techniques require that their data is sorted in order to achieve greater efficiency (speed). But the linear search makes no such requirement. The result is that the linear search may be slower than one might desire, but it always works, and one never needs to pay the (expensive) price of sorting the data before searching it.

True/False: The fact that the System.out.println() method is able to handle such a wide variety of objects, and print them correctly, is an example of the polymorphic nature of the println() method.

ANS: T Precisely! Since println() is highly polymorphic in nature, it is able to print a wide variety of pre-defined (library) and built-in (primitive) data correctly.

True/False: Some problems are easier to solve recursively than iteratively.

ANS: T Since recursion performs backtracking automatically, any problem that requires backtracking is easier to solve using recursion. In some cases, it is easy to find a recursive solution and so the recursive solution is easier than the iterative solution.

True/False: A polymorphic reference can refer to different types of objects over time.

ANS: T That is what polymorphism is all about: late binding. This means that the same name will be associated with different semantics as the program executes.

True/False: An interface reference can refer to any object of any class that implements the interface.

ANS: T This is one of the polymorphic functions of using an interface name to declare a reference variable.

True/False: A reference variable can refer to any object created from any class related to it by inheritance.

ANS: T This is the technique that one uses to accomplish a polymorphic reference--one whose precise interpretation will change during execution, depending upon the precise object to which the variable refers when it is encountered.

True/False: The protected visibility modifier provides the best possible encapsulation that permits inheritance.

ANS: T protected limits visibility as much as possible, while still allowing inheritance. In some ways, protected "advertises" that inheritance should be used.

True/False: The difference between the throw reserved word and the throws reserved word is that throw is used within a method body, while throws is used within a method header.

ANS: T throw is an imperative command that is used within a method to create and throw a new exception. throws is a compiler directive that tells the compiler that the current method may issue a throw that is not caught within the method and thus may escape to an outer level.

Recursion in java is

a process in which a method calls itself continuously. A method in java that calls itself is called recursive method.

private visibility modifier

classes and interfaces: Can only be applied to inner classes. Visible to the enclosing class only. methods and variables: not visible by any other class

protected visibility modifier

classes and interfaces: can only be applied to inner classes. Visible in its package and to classes that extend the class in which it is declared methods and variables: visible to any class in the same package and to any derived classes.

public visibility modifier

classes and interfaces: visible anywhere methods and variables: visible anywhere

Default visibility means that

no visibility modifier was explicitly used. Default visibility is sometimes called package visibility, but you cannot use the reserved word package as a modifier classes and interfaces: visible in its packge methods and variables: visible to any class in the same packageas its class


Related study sets

Business Strategy: Differentiation, Cost Leadership, and Blue Oceans

View Set

Life Only, Chapter 6 - F. Sales and Marketing of Life and Annuities

View Set

HIPAA and Privacy Act Training -JKO

View Set