CUS 1116 Final Exam Review

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

A solution with exponential complexity is ____________________ . a) efficient b) inefficient c) easy to implement d) difficult to implement e) none of the above

(B.) (inefficient) A solution with exponential complexity is very inefficient.

A(n) ____________________ is used to specify how certain exceptions should be handled. a) finally block b) try block c) catch block d) error e) none of the above

(C.) (catch block) A catch block specifies the actions to be performed when a particular exception is thrown in a try block.

The ________________ reference always refers to the currently executing object. a) null b) static c) final d) actual e) this

(E.) (this) The this reference always refers to the currently executing object. A null reference is a reference that is not pointing to any object. The other three choices are not special references in Java.

An object can be thought of as a blueprint for a set of classes.

False A class can be thought of as a blueprint for a set of objects; not the other way around.

Consider a reference declared in the following manner. Animal a; This reference may only point to an object that created by instantiating the Animal class.

False This reference may point to an object of any type that is compatible with Animal. In particular, it may point to any object that is an instance of a class that is a subclass of Animal.

Aggregation is sometimes described as a has-a relationship.

True Aggregate objects are objects that contain other objects as instance variables. Therefore the relationship between an object that is an aggregate of other objects is often described as a has-a relationship.

In Java, a subclass can only extend one parent class.

True Allowing a subclass to extend multiple parent classes leads to multiple inheritance, which is not supported in Java.

Describe a recursive solution to the Towers of Hanoi puzzle with N disks.

(1) Move the top N-1 disks to the extra peg. (2) Move the largest disk from the original peg to the destination peg. (3) Move the N-1 disks from the extra peg to the destination peg. The first step is the same problem again, with the extra peg and the destination peg interchanged, and therefore this subproblem can be solved recursively. The base case is when N = 1, in which case we simply move the disk without any recursive call.

What is an abstract class, and why might it be useful in an inheritance hierarchy?

An abstract class is a class represents a partially defined concept in an inheritance hierarchy. Abstract methods cannot be instantiated, but they can be extended. They are often useful because several classes may include common functionality but may lack a fully defined parent concept. Abstract classes allow a programmer to implement the partially defined parent concept as an abstract class which will include the common functionality of the child classes. An example of an abstract concept in an inheritance hierarchy might be a Vehicle. Subclasses like Car, Boat and Airplane are more fully defined, but they share common states and behaviors.

Why can't an interface be instantiated?

An interface cannot be instantiated because, similar to an abstract class, it only contains abstract methods.

Draw a hierarchy of Animals. The hierarchy should include the following entities: Animal, Reptile, Mammal, Bear, Human, Iguana, and Dolphin. Note that an Iguana is a Reptile, a Bear is a Mammal, a Human is a Mammal, and a Dolphin is a Mammal.

Animal / \ Reptile Mammal / / | \ Iguana Bear Human Dolphin

Methods that can be called directly through the class name and do not need to have an object instantiated are called _________________. a) final b) public c) static d) private e) none of the above

(C.) (static) Methods that can be called directly through the class name must be declared as static. Choices b) and d) are visibility modifiers for a method. Methods declared as final cannot be overridden.

Let Dog be a subclass of Animal, and suppose Animal has a method called speak() that is overridden in the Dog class. Consider the following code. Animal spot = new Dog(); spot.speak(); Which of the following is true? a) This code will result in a compile-time error. b) This code will result in a run-time error. c) The speak method defined in the Animal class will be called. d) The speak method defined in the Dog class will be called. e) The speak method will not be called at all.

(D.) (The speak method defined in the Dog class will be called.) The speak method defined in the Dog class will be called in this case. At run-time, the Java virtual machine determines that spot is pointing to an object of type Dog and binds the method to the methods defined in the Dog class.

Which of the following method headers is most likely a header for a mutator method? a) public int getAge() b) public double computeSalary() c) public Person() d) public void setAge(int newAge) e) none of these are headers for a mutator method

(D.) (public void setAge(int newAge)) Mutators are methods that change the value of an instance variable, and are often referred to as "setters." Therefore, choice d) is the correct answer. Choice a) is an example of a header for a accessor method, often referred to as a "getter." Choice c) is a constructor, and choice b) is a class method.

A method that calls itself is a __________________ method. a) invalid b) static c) final d) recursive e) public

(D.) (recursive) A recursive method is a method that calls itself.

All methods (with the exception of constructors) must specify a return type. What is the return type for a method that does not return any values? a) int b) public c) double d) void e) none of the above

(D.) (void) Methods that do not need to return any data should have void specified as the return type. A method cannot have public specified as its return type, so choice b is incorrect. Choices a) and c) specify a return type, and therefore they must return data of that type.

Write the recursive definition of the factorial of a number.

1! = 1 n! = n * (n - 1)! for n > 1

Explain what it means for a child class to override a method in a parent class. Why might this be useful?

A child class overrides a method that is inherited from a parent class by redefining it in the subclass. This is useful because a subclass may have a slightly different behavior than the superclass, but the behavior still has the same name. Overriding methods allows for this flexibility.

Can a class be a parent of more than one subclass? Can a class be a child of more than one parent? Explain.

A class can be the parent of more than one subclass in an inheritance hierarchy. Classes that have the same parent class are often called siblings. In Java, a class cannot be the child of more than one parent since Java does not support multiple inheritance.

What is the difference between an object and a class?

A class can be thought of as the blueprint for an object. In other words, the object is the embodiment of a class.

What does it mean for a class to be declared as final? What does it mean for a method to be declared as final?

A method declared as final cannot be overridden by any subclass. A class declared as final can not be extended via inheritance.

How does a method throw an exception?

A method throws an exception by using the throw statement.

What is polymorphism?

A polymorphic reference is a single type of reference that can point to different types of objects at different times. Polymorphism refers to the fact that the method calls on polymorphic references are selected by the object type, not the reference type. This is often referred to as late binding.

What is the difference between a service method and a support method in a class definition?

A service method is used to access or modify the data values of an object. They generally have public visibility. Support methods are designed to be used by service methods to support the tasks that the service methods perform. Support methods generally have private visibility.

What is a shadow variable?

A shadow variable is a variable that is declared in a subclass that has the same name as a variable declared in the class's parent class.

Explain how a subclass can can access its parent classes private instance variables and methods.

A subclass can access private instance variables and methods of its parent class, but only indirectly. There must be public methods that access the private data and methods directly. These public methods can then be called by the subclass, which gives indirect access to the private variables and methods of the parent class.

What is a try block?

A try block is a block of statements that may throw an exception.

What is encapsulation? How can it be enforced in Java?

Encapsulation is the principle that objects should be self-governing. In other words, an object's internal data should be protected from outside access. Encapsulation can be enforced in Java by making instance variables private.

Explain the relevance of the Object class to the Java programming language.

Every class in Java is a subclass of the Object class. This occurs whether a class definition explicitly extends the Object class or not. Therefore, every class in Java has a common set of methods that are defined in the Object class. These include the toString method and the equals method.

The Fibonacci sequence is defined as the sequence that begins with 0 and 1, and every other number in the sequence is the sum of the two preceding numbers. Write a recursive mathematical definition of the numbers in the Fibonacci sequence.

F(1) = 0 F(2) = 1 F(n) = F(n-1) + F(n-2) for n > 2

Every line in a catch block is guaranteed to be executed in all situations.

False A catch block may not be executed at all. It is only executed when an exception is thrown. All lines in a finally block are guaranteed to be executed.

A finally clause is always required in a try-catch block.

False A finally clause is optional.

A program with infinite recursion will act similarly to a program with an infinite loop.

False A program with infinite recursion will run out of memory. This will cause the program to crash. A program with an infinite loop will appear to "hang."

Polymorphism via inheritance requires that all classes in the inheritance hierarchy are concrete.

False A reference variable can be declared at the level of an abstract class. Objects that it refers to must be instantiated from concrete classes.

A reference variable can refer to an object of a child class, but not any further down the inheritance hierarchy.

False A reference variable can refer to an object of any class that is a descendent of the class of the reference variable.

Some problems can only be solved recursively.

False Any problem that can be solved recursively can also be solved iteratively.

The Towers of Hanoi puzzle cannot be solved iteratively.

False Any problem that can be solved recursively can also be solved iteratively. Therefore the Tower of Hanoi puzzle must have an iterative solution.

Attempting to divide by zero will result in an Error being thrown, not an Exception.

False Attempting to divide by zero will result in an ArithmeticException being thrown. An Error is typically reserved for more serious, unrecoverable problems in a program.

Unchecked exceptions must be caught or propogated, or a program will not compile.

False Checked exceptions must be caught or propogated. Unchecked exceptions do not have to be caught.

In the Towers of Hanoi puzzle, it is legal to move a larger disk to a peg that already contains a smaller disk.

False In the Towers of Hanoi puzzle, the only valid moves move a disk to a peg that only contains smaller disks.

In practice, it is important to catch all exceptions that might be thrown by a program.

False It is important for the programmer to consider the possible exceptions and to determine which exceptions are important to handle for a given application.

Recursive solutions are always more efficient than iterative solutions.

False Some recursive solutions are very efficient, but some are very inefficient.

The getMessage method of the Exception class prints out the stack trace, which helps the user to track down the source of the exception.

False The printStackTrace method prints out the stack trace.

Recursive solutions to problems should be used whenever possible.

False There are some cases where the iterative solution is less complex and more straighforward to code. In these cases, recursion is not the best choice.

Explain the difference between actual parameters and formal parameters.

Formal parameters are used in the definition of a method, while actual parameters are the values that are used in the method call.

How must IOExceptions be addressed in a program?

IOExceptions must either be caught, or the methods in the propagation sequence must all contain throws IOException in their headers.

What is the difference between a checked exception and an unchecked exception?

If a program includes a method call that may throw a checked exception, it is required to either explicitly catch it or throw it in order for the program to compile. An unchecked exception may be caught, but it does not require explicit handling for the program to compile.

What is exception prorogation, and how does it work in Java?

If an exception is not caught by the method in which it is thrown, it will be thrown to the method which called that method. If it is not handled there, it will be thrown to the method that called that method, and so on. This is called exception propagation. An exception will be propagated until it is caught and handled or until it is passed out of the main method. This will cause the program to terminate and print a message about the exception.

What are the standard I/O streams?

In Java, the standard I/O streams are System.in, System.out, and System.err.

How is a finally clause different from a try block and a catch clause?

In a finally clause, every statement is guaranteed to be executed, whereas every statement in a try block or a catch clause may not be executed.

Can a polymorphic reference invoke a method that is only declared at the object's class level? If "yes", explain how.

In general, a polymorphic reference can only be used to invoke methods that are known to the class of the reference variable. In order to call a method that is declared at the object's class level, the reference variable must be cast to be of the object's type as part of the call.

How does inheritance relate to polymorphism in Java?

Inheritance is one process by which polymorphic references are created. A reference to a type higher in an inheritance hierarchy can always refer to an object of a type lower in an inheritance hierarchy due to the is-a relationship.

Explain why inheritance is useful.

Inheritance is useful because it allows for code-reuse. This means that if we have multiple software entities that have common features, the code for the common features can be written once in a superclass. The classes that include these features can then be written via inheritance, and this common code does not have to be rewritten.

What is instance data?

Instance data refers to the data that will be stored in each object of a class. New memory space is allocated for instance data every time that an object is created. Each object of a class has its own unique memory allocation, so that its instance data is unique from that of any other objects of the same class.

When a reference variable refers to an object that is in an inheritance hierarchy and a method of the object is invoked, how does Java determine which version of the method to use?

Java determines the definition of the method that is closest to the object in the inheritance hierarchy between the reference variable and the object.

Write a recursive definition for K(n), which represents the product of all of the even integers less than or equal to n.

K(1) = 0 K(2) = 2 K(n) = n * K(n-2) if n is even and greater than 2 K(n) = K(n-1) if n is odd and greater than 2

Explain why method overloading is useful.

Method overloading is useful because it allows multiple methods to have the same name as long as they have different parameter types. This allows for more flexibility in choosing identifiers for methods, since the alternative would require the programmer to have different method identifiers for every method that took in a different type of parameter.

Is the Exception class a subclass of the Error class? Explain.

No, the Exception class is not a subclass of the Error class, because there is no is-a relationship between them. They are actually siblings in an inheritance hierarchy. They are both subclasses of the Throwable class.

Can a static method access instance data in a class?

No. Static methods are defined at the class level. Instance data is allocated at the object level. Static methods do not have access to object level data.

Java uses pass by value for passing parameters on a method call. What does this mean if the parameter is a primitive data type? What does this mean if the parameter is a reference to an object?

Pass by value means that the value associated with the actual parameter is copied into the memory location of the formal parameter when the method is called. The formal and actual parameters occupy distinct locations in memory. If the parameter is a primitive data type, any modifications made to the formal parameter during the execution of the method will most likely not be reflected in the actual parameter. If the parameter is a reference to an object, then it holds the location of an object. While the formal and actual parameters will be distinct, they will both hold the address of the object and will be aliases. If the method modifies the object, then those modifications will be apparent when referencing the object using the actual parameter after the method terminates.

How can a print() or println() statement be used in debugging?

Print statements can be used to show the contents of variables at specific points in the code execution. This can be useful if a program produces incorrect results and the programmer or tester is trying to detect where an incorrect value first appeared in the code.

What is recursion?

Recursion is a common programming technique where a method calls itself.

Give a recursive definition of the sum of the first n integers, S(n).

S(0) = 0 S(n) = n + S(n - 1) for n > 0

Consider a software system that will implement the following classes: Student, Professor, StaffMember, ContractWorker. List some common attributes of these classes. What would be a good abstract class from which these classes may be extended via inheritance?

Some common attributes would be socialSecurityNumber, age, and address. A good abstract class from which these classes could be extended is Person.

Give an example of how a static variable can be used in a class.

Suppose that a program needs to keep track of how many objects of a particular class have been created. Declaring and managing a counter at the program level could be a complex task. It might be simpler to let the class itself maintain the counter. A static int variable could be declared at the class level to be used as a counter. All of the constructors of the class could increment the static variable. A static method would also be needed to return the value of the counter.

A programmer tries to create a subclass of String called MyString. When the programmer compiles her new class, the compiler produces the following message: MyString.java:1: cannot inherit from final java.lang.String public class MyString extends String { ^ 1 error Explain the cause of this error.

The String class has been declared with the final modifier, which restricts any other classes from extending it.

Give an example of a class that implements the Comparable interface, and explain how the implementation of the compareTo method determines its return value.

The String class implements the Comparable interface. The comparison is based on the lexicographic ordering of String objects defined by the Unicode character set.

What is/are the base case(s) when calculating the sum of the first n positive integers recursively?

The base case occurs when n = 1, the smallest positive integer.

What is a catch clause?

The catch clause is the part of the try statement that catches an exception that may be thrown in the try block.

Describe the compareTo method and the circumstances under which it returns different values.

The compareTo method is specified by the Comparable interface. It places an ordering on objects. Consider the following call to compareTo: int result = obj1.compareTo(obj2); In this case result will be positive if obj1 is larger than obj2 in the sense of the ordering. It will be 0 if obj1 and obj2 are the same, and it will be negative if obj2 is larger than obj1.

Consider the following inheritance hierarchy that is used in a video game. Character / \ Friend Villain / \ / \ WiseMan ShopKeeper Dragon Skeleton | | FlyingDragon EliteSkeleton Which of the following declarations and initializations will not cause a compiler error? Character c = new FlyingDragon(); FlyingDragon f = new Character(); Dragon d = new Villain(); Villain v = new Skeleton(); Dragon d = new ShopKeeper();

The following are valid for this inheritance hierarchy because of the is-a relationship. Character c = new FlyingDragon(); Villain v = new Skeleton();

Method overloading requires that the methods have different signatures. What parts of a method are used in the signature?

The method name, the number of parameters, the types of the parameters, and the orders of the parameters are all part of the method signature.

Consider a class hierarchy that includes a class called Vehicle, with subclasses called Car and Airplane. The Vehicle class has a method called getMaxSpeed, which is overridden in the Car class. The getMaxSpeed of the Vehicle class returns 760 mph, while the getMaxSpeed method of the Car class is overridden to return 150 mph. What is the output of the following snippet of code? Explain your answer. Vehicle v = new Car(); System.out.println(v.getMaxSpeed() + " mph");

The output of this code will be "150 mph". Even though the reference is to the Vehicle class, the getMaxSpeed method is bound to the definition in the Car class, since the object is a car. This is due to the polymorphic nature of the reference.

Give two examples of methods in the Exception class that can be used to output information about the Exception.

The printStackTrace and the getMessage methods can be used to output information about a particular Exception object.

Compare and contrast the private visibility modifier to the protected visibility modifier. Why is the protected visibility modifier a better choice in an inheritance hierarchy?

The private modifier and the protected modifier both enforce the encapsulation of instance variables and methods in a class. This means that unrelated classes are not able to directly access the variables and the methods. The protected modifier, however, does allow for the instance variables and the methods to be accessed by subclasses of the original class. This makes the protected modifier a better choice for use in an inheritance hierarchy, because it is often useful for subclasses to have access to a superclass's instance variables and methods.

How are input and output streams similar? How are they different?

The similarity is that they are both streams, which are ordered sequences of bytes of data. They differ in their purpose: input streams are meant to be used by a program for input, that is, as a source of data. Output streams are meant to be used by a program for output, that is, to hold some part of the results that were computed in the program.

Describe the behavior of the toString method and the equals method of the Object class.

The toString method returns a String representation of an object. The equals method returns true if the object is an alias of the object sent in as a parameter.

Why is it considered a good practice to override the toString and equals methods?

These methods are defined in the Object class and are inherited by all classes. By overriding these methods, a programmer can define behavior that more closely matches the purpose of the class, rather than using the default behavior as defined in the Object class.

How are unit testing, integration testing, and system testing related? How are they different?

They are related in that they are all forms of software testing. They differ in respect to the size (the amount of code) that they test. Unit testing tests the individual modules or components as units. These units may be individual classes or methods. Integration testing combines several related units and tests them as a collective entity. System testing tests the overall software system as a whole, which is comprised of several sets of software that have passed integration testing.

Consider the following code fragment. int [] a = new int[50]; a[50] = 100; Will this code fragment throw an exception? Explain.

This code will throw an ArrayIndexOutOfBoundsException since the indexes of a run from 0 to 49, and this code fragment tries to access index 50.

What is wrong with the following recursive method that computes the sum of all of the odd positive integers less than or equal to n?

This method has no base case, and therefore running it would cause infinite recursion.

In Java, it is possible for a method to call itself.

True A method that calls itself is a recursive method.

A throw statement is used to begin exception propagation.

True A throw statement begins the propagation of an exception.

An interface cannot declare any instance variables.

True An interface may declare constants, but it may not declare instance variables.

An interface name may be used as a reference type.

True An interface name may be used a reference type in the same way that a class name may be used as a reference type. Like an abstract class, an interface cannot be instantiated, however.

A return statement is not required at the end of every method.

True Constructors and methods with a return type of void do not require return statements.

All recursive methods must have a base case.

True If a recursive method does not have a base case, it will yield an infinite recursion which will crash a program.

An exception will be propagated until it is caught and handled or until it is passed out of the main method.

True If an exception is not caught and handled, it will be propagated until it is passed out of the main method.

Determining whether or not there is a path through a maze has a recursive solution.

True It is possible to traverse a maze recursively, and therefore there is a recursive solution to determining whether or not there is a path through a maze.

Files that are open for output from a program must be explicitly closed in the program.

True Output files must be closed before a program ends to ensure that all of the expected output is in the file.

Establishing the relationship between a listener and the component it listens to is accomplished using polymorphism.

True The association between a component and its listener is performed by using the component's addActionListener method. The parameter to addActionListener is a reference to an object of the ActionListener interface. The listener object must implement the ActionListener interface and provide a body for the performAction method, which the component invokes when an event occurs.

When accessing an element of an array, if the index is outside of the range of the indexes of the array, an exception is thrown.

True This is a situation where an ArrayIndexOutOfBoundsException will be thrown.

A method that calls a different method, which then calls the original calling method is a recursive method.

True This is an example of indirect recursion.

A child class is allowed to declare a variable with the same name as one that is contained in the parent class.

True This is known as variable shadowing and can lead to confusion. It is, however, permitted in Java.

Is an exception an object? Explain.

Yes, an exception is an object in Java. It is defined by a class, which is a subclass of the Object class. Therefore, it has all of the features of every other object type in Java.

Suppose we create a subclass from a class that has a method called someMethod. If we override someMethod in the subclass, is it possible to access the superclass's version of someMethod? If so, how?

Yes, it is possible to access the original version of the method. To do so, we qualify the call to the method with the super reference. In other words, to access the original version of the method we call super.someMethod().

Does polymorphism work if some of the classes in an inheritance hierarchy are abstract?

Yes. A reference variable can be declared at any level in the inheritance hierarchy. If it is declared to be of an abstract class, it can still be used to refer to objects of concrete classes.

Can an interface hierarchy be used for polymorphism? Explain.

Yes. A reference variable can use an interface as its type, and can then refer to objects of classes that implement the interface. In this way, polymorphism works the same as it does with an inheritance hierarchy.

Are there any differences between extending a class and implementing an interface?

Yes. First, extending a class uses the extends keyword, while implementing an interface uses the implements keyword. More importantly, a class can implement multiple interfaces, while it can only extend a single class.

Is dynamic binding used when polymorphic references are made using interfaces?

Yes. Java must use the type of the object to identify which method code to use for an invocation. This identification is done at execution-time, not at compile time, and is therefore considered dynamic binding.

Write a short snippet of code that converts the first element of the String[] args array to an integer. It should catch an exception and print out a message if the first element cannot be converted to an integer.

int number; try { number = Integer.parseInt(number); } catch(NumberFormatException nfe) { System.out.println("The first argument to the command line" + " is not an integer; try again."); System.exit(0); }

Write a code fragment that will throw an ArithmeticException. Your code fragment should not use the throw statement.

int zero = 0; int num = 5; int result = num/zero; System.out.println(result);

Describe a recursive solution to determine whether a String object is a palindrome. You may assume that the string only contains lower case characters (i.e. no numbers, spaces, punctuation, etc). Hint: It may be easiest to describe your solution using pseudocode.

isPalindrome(String s) if the length of the string is 1 return true else if the length of the string is 2 and the two characters are the same return true else if the first and the last characters are the same return isPalindrome(the string created by removing the first and last characters) else return false

The Lucas sequence is defined as the sequence that begins with 2 and 1, and every other number in the sequence is the sum of the two preceding numbers. A recursive method to generate the nth term in the Lucas sequence is: public int lucas(int n) { if(n == 1) return 2; if(n == 2) return 1; return lucas(n-1) + lucas(n-2); } When calculating lucas(8), how many times is lucas(5) calculated?

lucas(8) calls lucas(7) and lucas(6). Each of these makes calls also. Here is a partial call tree down to lucas(5): lucas(8) / \ lucas(7) lucas(6) / \ / \ lucas(6) lucas(5) lucas(5) lucas(4) / \ lucas(5) lucas(4) There are 3 calls to lucas(5), so lucas (5) is calculated 3 times in the calculation of lucas(8).

A main method can only access static or local variables.

True A main method cannot access non-static and non-local variables because it is a static method. In particular, it cannot access any variables declared at the class level.

A parameter to a method can be polymorphic.

True A method can accept a polymorphic reference; this may give the method more flexibility than it would otherwise have.

A child class is allowed to define a method with the same name and parameter list as a method in the parent class.

True A subclass is allowed to override methods that are in the parent class.

In a class that has variables called height and width, methods called getHeight() and getWidth() are examples of accessor methods.

True Accessor methods return the value of instance variables. They are often named using the word 'get' followed by the name of the instance variable.

Compile-time binding is more efficient than dynamic binding.

True Binding is the process of connecting method code to a method invocation/call. Compile-time binding occurs when the code is compiled. The connection is made once. Dynamic binding occurs when the program runs. For each call, the program must determine which code to use, and then execute the code. The need to determine the code to invoke for each call during program execution makes dynamic binding slightly less efficient than compile-time binding.

Private members of a parent class are inherited by child classes.

True Child classes inherit all of the members of a parent class, whether they are public, private, or protected. Private members cannot be accessed directly (by name) in the child class, but they are part of the derived class.

Every class has a constructor, whether defined by the programmer or not.

True Every class automatically has a default constructor that doesn't take any parameters. The default constructor is used when objects are created if no other constructor is defined.

Variables that are declared as static are shared among all instances of a class.

True Static variables are sometimes called class variables because they are shared among all instances of a class.

It is possible to derive a class from an abstract class without overriding all of the parents abstract methods.

True The child class must also be declared as abstract in this case.

Student is a class that has the following instance variables: name (a String), yearInSchool (an int), and gpa (a double). Write a constructor for the Student class that takes parameters for these instance variables as initial values of the variables. Use the this reference in the constructor.

public Student(String name, int yearInSchool, double gpa) { this.name = name; this.yearInSchool = yearInSchool; this.gpa = gpa; }

Write a method called isPalindrome that accepts a String as a parameter and returns true if the String is a palindrome, and false otherwise. You may assume that the entered String consists entirely of lowercase letters (meaning it contains no numbers, spaces, punctuation, etc). Hint: write code that creates a new string that is the original string reversed, and then check to see if the two strings are equal.

public boolean isPalindrome(String s) { String reverseS = new String(""); for(int i = s.length()-1; i >= 0; i--) reverseS += s.charAt(i); return reverseS.equals(s); }

Write a recursive Java method that takes a String as a parameter and returns true if the String is a palindrome. You may assume that the string only contains lower case characters (i.e. no numbers, spaces, punctuation, etc).

public boolean isPalindrome(String s) { if(s.length() == 1) return true; else if(s.length() == 2 && s.charAt(0) == s.charAt(1)) return true; else if(s.charAt(0) == s.charAt(s.length() - 1)) return isPalindrome(s.substring(1, s.length() - 1)); else return false; }

Suppose you are implementing the comparable interface in a class representing a Person, where the ordering is based on the age of the person. Write a compareTo method for this class. You may assume that there is an instance variable called age and an accessor method called getAge.

public int compareTo(Object o) { Person p = (Person) o; return this.getAge() - p.getAge(); }

Write a recursive method that returns the factorial of an integer.

public int factorial(int n) { if(n == 0) return 1; else return n*factorial(n-1); }

The Fibonacci sequence is defined as the sequence that begins with 0 and 1, and every other number in the sequence is the sum of the two preceding numbers. Write a recursive method that computes the nth number in the Fibonacci sequence.

public int fibonacci(int n) { if(n == 1) return 0; if(n == 2) return 1; return fibonacci(n-1) + fibonacci(n-2); }

Write a recursive method that computes the product of all of the even integers less than or equal to n.

public int productOfEvens(int n) { if(n <= 1) return 0; if(n == 2) return 2; if(n%2 == 0) return n*productOfEvens(n-2); else return productOfEvens(n-1); }

Write a method called randomInRange that takes in two numbers representing a range. Print an error message and return zero if the second parameter is less than the first. Otherwise, the method should return a randomly generated integer in that range (inclusive). You may assume that the class has a static Random object called generator already declared and instantiated.

public int randomInRange(int a, int b) { if(b < a) { System.out.println("Error, invalid range!"); return 0; } return generator.nextInt(b - a + 1) + a; }

Write a recursive method that computes the sum of the first n integers.

public int sum(int n) { if(n == 0) return 0; else return n + sum(n-1); }

Write an interface for a CD player. It should have the standard operations (i.e. play, stop, etc) that usual CD players have.

public interface CDPlayer { public void play(); public void stop(); public void nextTrack(); public void previousTrack(); public void seekForward(); public void seekBackwards(); }

Suppose Animal is an interface that specifies a single method - speak. Now suppose the Dog class implements the Animal interface. In addition to the speak method, the Dog class also has a method called wagTail. Now consider the following code. Animal a = new Dog(); a.wagTail(); Which of the following is true about this code? a) It will result in a compile-time error. b) It will result in a run-time error. c) It will call the speak method defined in the Animal interface. d) It will call the wagTail method defined in the Dog class. e) none of the above are true.

(A.) (It will result in a compile-time error) This code will result in a compile-time error since the Animal interface does not specify a wagTail method. This compile-time error can be avoided by explicitly casting a as a Dog when calling the wagTail method.

Which of the following exceptions are unchecked? a) RuntimeException b) IllegalAccessException c) NoSuchMethodException d) ClassNotFoundException e) none of the above

(A.) (RuntimeException) All subclasses of the RuntimeException class are unchecked.

Which of the following represents the standard input stream? a) System.in b) System.out c) System.err d) System.instream e) System.outstream

(A.) (System.in) The standard input stream is represented by System.in.

The Exception class and the Error class are subclasses of the ___________________ class. a) Throwable b) Catchable c) RuntimeProblem d) CompilerProblem e) none of the above

(A.) (Throwable) The Throwable class is the parent class of the Error and Exception classes.

The _______________________ puzzle is a favorite of computer scientists because of its elegant recursive solution. a) Tower of Hanoi b) Sudoku c) Tetris d) Tic-Tac-Toe e) none of the above

(A.) (Tower of Hanoi) The Tower of Hanoi puzzle has an elegant recursive solution, and has therefore become a favorite of computer scientists.

Which GUI concepts use polymorphism to establish their relationship? a) a listener and its associated component b) a radio button and its default selection c) a button and its label d) a slider and its tick marks e) none of the above

(A.) (a listener and its associated component) Polymorphism is used to establish the relationship between a listener and its associated component.

In Java, polymorphic method binding occurs ____________________ . a) at run time b) at compile time c) never d) when a programmer writes the code e) during the testing phase of software development

(A.) (at run time) polymorphic method binding occurs at run-time.

A(n) _____________________ is an object that defines an erroneous situation from which the program usually cannot recover. a) error b) exception c) interface d) try block e) catch block

(A.) (error) An error is similar to an exception in that it is an object that represents and erroneous situation, but it typically cannot be recovered from.

The recursive solution of the Towers of Hanoi problem has _______________ complexity. a) exponential b) polynomial c) logarithmic d) low e) none of the above

(A.) (exponential) The recursive solution of the Towers of Hanoi problem has exponential complexity, which means that it is significantly inefficient.

When designing a class hierarchy, it is important that common features be ________________________ . a) higher in the class hierarchy. b) lower in the class hierarchy. c) near the middle of the class hierarchy. d) in abstract classes. e) in the Object class.

(A.) (higher in the class hierarchy.) Common features should be included closer to the top of the class hierarchy. Doing this makes them available to more classes lower in the hierarchy.

In Java, polymorphic references can be created through the use of __________________ and ________________. a) inheritance, interfaces b) inheritance, abstract classes c) interfaces, abstract classes d) interfaces, iterators e) none of the above

(A.) (inheritance, interfaces) In Java, polymorphic references can be created through the use of inheritance and interfaces.

The process of inheritance should establish a(n) ___________________ relationship. a) is-a b) has-a c) static d) not-a e) none of the above

(A.) (is-a) Inheritance should establish an is-a relationship. Therefore any objects that are of a type lower in the inheritance hierarchy are also of a type higher in the inheritance hierarchy.

Which of the following file streams should be explicitly closed to ensure that written data is properly retained? a) output b) input c) error d) writable e) readable

(A.) (output) Output file streams should be explicitly closed using the close method so that all data is properly retained.

A method that has multiple definitions is an __________________ method. a) overloaded b) overridden c) overlooked d) overclocked e) none of the above

(A.) (overloaded) A method that has multiple definitions is an overloaded method. The versions of an overloaded method are distinguished by the number, type and order of their parameters. Overridden methods are methods that have been redefined later in an inheritance hierarchy. They will be studied in more detail later. Choice c and d are not types of methods in Java.

Regression testing refers to a) re-testing a program after fixing a problem to ensure that the fix worked and that it did not introduce another problem. b) executing the statements in the program in reverse order. c) executing the program on many different types of computers and comparing the results. d) running a program with many different sets of inputs. e) None of these describes regression testing

(A.) (re-testing a program after fixing a problem to ensure that the fix worked and that it did not introduce another problem.) Once an error is found and fixed, regression testing is the process of re-testing the program to both determine that the original problem is fixed and to detect if any new errors were introduced by the fix. Choice d) - running a program with many different sets of inputs - refers to the general notion of designing sets of inputs to exercise as many branches of a program as possible.

A _______________ variable is shared among all instances of a class. a) static b) final c) public d) private e) none of the above

(A.) (static) A static variable is shared among all instances of a class. A final variable is a constant, a public variable is one that is accessible from outside the object and a private variable is one that cannot be accessed outside of the object.

The versions of an overloaded method are distinguished by ___________________________. a) the number, type and order of their parameters b) their identifiers c) their classes d) the number and type of their parameters e) the number of their parameters

(A.) (the number, type and order of their parameters) Overloaded methods are two methods in the same class that have the same identifier, but a different number, type or order of parameters. Therefore, choice a) is correct and the rest are incorrect.

In the Towers of Hanoi puzzle, there are ________________ pegs. a) 2 b) 3 c) 4 d) 5 e) The Towers of Hanoi puzzle can include any number of pegs

(B.) (3) In the Towers of Hanoi puzzle, there are always exactly three pegs.

How many base cases must a recursive method have? a) A recursive method does not have to have a base case. b) at least 1 c) more than 1 d) more than 2 e) more than 3

(B.) (At least 1) Every recursive method must have at least one base case. It may have more, but it must have at least one.

Suppose that Horse is a subclass of Animal, and neither class is abstract. Which of the following is an invalid declaration and initialization? a) Horse h = new Horse(); b) Horse h = new Animal(); c) Animal a = new Animal(); d) Animal a = new Horse(); e) all of the above are valid

(B.) (Horse h = new Animal();) Since Horse is a subclass of Animal, choice b would require an explicit cast in order to be valid.

Let Object a be larger than Object b. What will the following method call return? a.compareTo(b) a) it will return 0 b) it will return a number greater than 0 c) it will return a number less than 0 d) it will return true e) it will return false

(B.) (It will return a number greater than 0) The compareTo method returns an integer. If Object a is bigger than Object b, it will return a number greater than 0.If Object a is less than Object b, it will return a number less than 0. If they are equal it return 0.

__________ occurs when a child class defines a method with the same signature as a method in the parent class. a) Overloading b) Overriding c) Overwhelming d) Substituting e) A child class cannot define a method with the same signature as a parent class method.

(B.) (Overriding) Overriding occurs when two methods, one in the parent class and one in the child class, have the same signature. The signature is the method name and the parameter list.

A ________________ diagram helps us visualize the contents of and relationships among the classes of a program. a) class and object b) UML c) object-oriented d) public e) private

(B.) (UML) A UML diagram helps us visualize the contents and relationships among the classes of a program. The other choices do not refer to any type of diagram.

Which of the following statements is not a general inheritance practice that you should keep in mind in the design of a program? a) Derived classes should have an "is-a" relationship with the parent classes. b) Use the final key word when defining parent classes. c) Avoid shadowing inherited variables when possible. d) Define abstract classes to specify a common class interface for concrete derived classes. e) All of these are general inheritance practices that should be considered when designing a program.

(B.) (Use the final key word when defining parent classes.) Using the final key word in a class header indicates that the class cannot be extended, or inherited from. It cannot be used in a class header if the class is intended to be the parent of one or more classes.

A(n)______________________ class represents a generic concept in a class hierarchy. a) super b) abstract c) interface d) shadow e) generic

(B.) (abstract) An abstract class represents a generic entity that is not completely defined. An abstract class cannot be instantiated. It contains one or more abstract methods, which are methods that should be overridden by subclasses.

A(n) ___________________ object is one that is made up, at least in part, of other objects. a) static b) aggregate c) encapsulated d) private e) public

(B.) (aggregate) An aggregate object is one that is made up of other objects. Choice a), d) and e) do not refer to types of objects. Encapsulated objects may be made up of primitive types or object types.

The commitment to execute certain code to carry out a method invocation is referred to as _________________. a) execution b) binding c) polymorphism d) inheritance e) none of the above

(B.) (binding) Binding refers to the commitment to execute certain code to carry out a method invocation.

A(n) ____________________ can be used to find the exact line where an exception was thrown during program execution. a) interface b) call-stack trace c) try block d) catch block e) none of the above

(B.) (call-stack trace) A call-stack indicates the exact line where an exception is thrown.

All recursive programs ____________________________________ . a) are more difficult to read than iterative programs. b) can be implemented iteratively. c) are easier to read than iterative programs. d) are shorter than iterative programs. e) none of the above are true.

(B.) (can implemented iteratively) All recursive programs can be implemented iteratively, although a recursive solution may be easier to code.

A class declared as final _________________________________ . a) cannot be changed. b) cannot have subclasses. c) cannot have superclasses. d) has several abstract methods. e) cannot be used in a program.

(B.) (cannot have subclasses.) The final modifier restricts inheritance. In particular, a class declared as final cannot have subclasses.

A(n) _____________________ is an object that defines an unusual or erroneous situation that is typically recoverable. a) error b) exception c) interface d) try block e) catch block

(B.) (exception) An exception is an object that represents an erroneous situation, and it is usually recoverable.

Which of the following key words indicates a method that cannot be overridden in a derived class? a) super b) final c) extends d) inherits e) expands

(B.) (final) The key word final, when used in a method header, indicates that the method cannot be overridden in a derived class.

Late binding is _______________ than _______________ . a) more efficient, compile-time binding b) less efficient, compile-time binding c) more efficient, run-time binding d) less efficient, run-time binding

(B.) (less efficient, compile-time binding) Late binding is less efficient than compile-time binding due to the overhead associated with determining the code that should be executed at run time.

When a variable declared in a subclass has the same name as a variable declared in a superclass, it is called a _______________ variable. a) final b) shadow c) static d) dead e) this is not allowed in Java

(B.) (shadow) A shadow variable is a variable in a subclass with the same name as a variable in the superclass.

If an exception is not caught, a program will __________________________ . a) not compile b) terminate abnormally c) print a message and continue executing d) all of the above e) neither a, b nor c

(B.) (terminate abnormally) A program will terminate abnormally if an exception is thrown and not handled by a catch block.

Which of the following methods are included in every class created in Java by inheritance? a) next b) toString c) compareTo d) charAt e) none of the above

(B.) (toString) The toString method is defined in the Object class, and is therefore included in every Java class via inheritance.

There is(are) ____________ base case(s) in the recursive solution to finding a path through a maze. a) 0 b) 1 c) 2 d) 3 e) 4

(C.) (2) There are two base cases in the recursive solution to this problem. The two base cases are: (1) a path has been found, and (2) there is no way to move forward via the current path.

Of the classes below, the one that is most likely to be declared abstract is _________________. a) Bat b) Squirrel c) Animal d) Iguana e) Parrot

(C.) (Animal) The Animal class is most likely to be abstract since it is the most generic.

____________ is the process of catching an exception in the chain of method calls from the method where the exception occurred up to the main method. a) Error handling b) Exception handling c) Exception propagation d) Catch block nesting e) Finally block nesting

(C.) (Exception propagation) The statement defines the process of exception propagation.

__________________ recursion results from the lack of a base case. a) Indirect b) Direct c) Infinite d) Spiral e) none of the above

(C.) (Infinite) Infinite recursion results from the lack of a base case, which causes the recursive path to be followed forever.

Consider the following line of code. Comparable s = new String(); Which of the following statements is true about this line? a) It will result in a compile-time error. b) It will result in a run-time error. c) It will create a String object pointed to by a Comparable reference. d) Although it is perfectly valid Java, it should be avoided due to confusion. e) none of the above are true

(C.) (It will create a String object pointed to by a Comparable reference.) This is a valid Java statement and will result in no errors, since the String class implements the Comparable interface.

You need to create a reference variable that can refer to objects from many different classes. You do not know the inheritance hierarchies of the classes. The safest class to use to declare the reference variable is a) Animal b) String c) Object d) Scanner e) File

(C.) (Object) All classes are descendants of the Object class, so every object will have the Object class in its inheritance hierarchy.

Which of the following statements is true? a) Recursion should be used in every program. b) Recursion should be avoided all the time. c) Solutions that are easily expressed recursively should be programmed recursively. d) Solutions that are easily expressed recursively should be programmed iteratively. e) None of the above.

(C.) (Solutions that are easily expressed recursively should be programmed recursively). Recursion should be used when the solution is easily expressed recursively.

Which of the following exception types must always be caught unless they are contained in methods that throw them in the method header? a) file stream b) IO c) checked d) unchecked e) none of the above

(C.) (checked) Checked exceptions must always be caught or thrown, or else a compiler error will be generated.

A(n) __________________ is an application that displays the inner workings of an executing program. a) stethoscope b) telescope c) debugger d) signal analyzer e) oscilloscope

(C.) (debugger) Debugging is the act of locating and correcting run-time and logic errors in your programs. A debugger is a software application that allows us to observe the inner workings of a program as it executes. Choice a) is an analytic tool used in medicine. Choice b) is a tool used in astronomy. Choices d) and e) are used in analyzing hardware components.

____________________ recursion occurs when a method calls itself, while _________________ recursion when a method calls another method that then calls the original method. a) upward, downward b) downward, upward c) direct, indirect d) indirect, direct e) none of the above

(C.) (direct, indirect) Direct recursion occurs when a method calls itself, while indirect recursion occurs when a method calls another method that then calls the original method.

A polymorphic reference is one that can refer to _______________ type(s) of object(s). a) exactly one b) zero c) multiple d) abstract e) static

(C.) (multiple) A polymorphic reference can point to multiple types of objects at different points in time.

Which of the following methods are part of the Exception class and can be used to give information about a thrown exception? a) getInfo b) printInfo c) printStackTrace d) getStackTrace e) none of the above

(C.) (printStackTrace) The printStackTrace method can be used to give more information about a thrown exception.

If a service is so complex that it cannot be reasonably be implemented using one method, it is often helpful to decompose it to make use of ________________ support methods. a) static b) aggregate c) private d) public e) final

(C.) (private) Private support methods are useful when a service is too complex to be defined in a single method. Therefore choice c) is correct.

In order for derived classed to have access to encapsulated data members and methods of superclasses, the data members and methods should be declared using the ____________________ modifier. a) private b) public c) protected d) final e) static

(C.) (protected) Data members and methods declared using the protected modifier can be accessed by subclasses in an inheritance hierarchy, but are still encapsulated from classes and methods outside of the hierarchy.

Which of the following is a proper recursive definition of x raised to the y power? a) x^y = x * x^(y-1) b) x^y = x * x^(y-2) c) x^y = x * x^(y-1) for y > 1; x^y = x for y = 1 d) x^y = x * x^(y-1) for all x e) none of the above

(C.) (x^y = x * x^(y-1) for y > 1; x^y = x for y = 1) Choice c is correct because it has a properly defined base case.

Which of the following will result from infinite recursion in Java? a) The program will hang as though there is an infinite loop. b) The program will throw an ArrayOutOfBoundsException. c) The program will not compile. d) The program will run out of memory. e) none of the above.

(D.) (The program will run out of memory.) Infinite recursion will cause a program to run out of memory.

In a recursive solution, _______________ is(are) always necessary. a) short, efficient code b) several variables c) numerous lines of code d) a base case e) none of the above

(D.) (a base case) A base case is always necessary in a recursive solution to avoid infinite recursion.

The original class that is used to derive a new class using inheritance is called ____________________ . a) a superclass b) a parent class c) a base class d) all of the above e) neither a, b, nor c

(D.) (a superclass, parent class, base class) The original class can be called a superclass, a parent class, or a base class.

A(n) ________________ is a step-by-step process for solving a problem. a) UML diagram b) aggregate object c) class d) algorithm e) none of the above

(D.) (algorithm) An algorithm is a step-by-step solution for solving a problem. A UML diagram is a way of visually representing how classes and objects interact. An aggregate object is an object that is composed, in part, of other objects. A class can be thought of as a blueprint for a set of objects.

Which of the following methods are included with any object that implements the Iterator interface? a) next b) hasNext c) toString d) all of the above e) a and b

(D.) (all of the above) The Iterator interface specifies that all objects that implement it must have the hasNext and next methods. Since all objects in Java are a subclass of the Object class, it will also include the toString method.

The Comparable interface contains which of the following methods? a) isGreaterThan b) isLessThan c) equals d) compareTo e) all of the above

(D.) (compareTo) The Comparable interface contains exactly one method -- compareTo.

Which of the following types of methods do not have any return type (not even a void return type)? a) methods declared as static b) methods declared as public c) methods declared as private d) constructors e) all of the above have return types

(D.) (constructors) Constructors are the only methods that do not have any return type. They do not even have a void return type. All of the other methods must specify a return type or be declared as void.

In Java, a(n) ___________________ is a collection of constants and abstract methods. a) polymorphic reference b) abstract class c) implementation d) interface e) iterator

(D.) (interface) An interface is a collection of constants and abstract methods.

When applied to instance variables, the ________________ visibility modifier enforces encapsulation. a) static b) final c) public d) private e) none of the above

(D.) (private) The private visibility modifier guards against inappropriate data access, and therefore promotes encapsulation. Choices a) - static - and b) - final - are not visibility modifiers, and choice c) - public - is a visibility modifier that allows public access to an object's data, which violates the principle of encapsulation.

A(n) ________________ is an ordered sequence of bytes. a) exception b) error c) input-output flow d) stream e) none of the above

(D.) (stream) A stream is an ordered sequence of bytes.

To invoke a parent's constructor in a subclass, we use the ______________ method. a) abstract b) construct c) parent d) super e) extends

(D.) (super) To invoke a parent's constructor in a subclass, we use the ______________ method.

A(n) ____________________ is used to identify a block of statements that may cause an exception. a) call-stack trace b) error c) catch block d) try block e) none of the above

(D.) (try block) A try block is used to identify a block of statements that can throw an exception.

A child class can access private members of a parent class by a) using super in front of the member name b) using the member name directly c) using this in front of the member name d) using the public accessor and mutator methods defined in the parent class e) A child class cannot access private members of a parent class.

(E.) (A child class cannot access private members of a parent class.) Private members of a parent class cannot be accessed from an object of a child class directly or through the use of super. They can be accessed by using the public accessor and mutator methods that the parent class provides.

All Java classes are subclasses of the ___________________ class. a) String b) java.lang c) Java d) Class e) Object

(E.) (Object) All classes are subclasses of Java's Object class, whether explicitly specified or not.

In indirect recursion, how many method calls can occur between one call to a method and the next one that completes the indirect recursion a) 2 b) 3 c) 4 d) 5 e) There is no limit to the number of intervening calls between a method and its indirect recursive call.

(E.) (There is no limit to the number of intervening calls between a method and its indirect recursive call.) Java does not impose a limit on the number of intervening methods between a call to a method and a call that creates indirect recursion. From a practical standpoint, the fewer the number of calls, the simpler the program will be to understand and the easier the task of tracing the recursion should that become necessary.

Every line of a(n) __________________ is executed no matter what exceptions are thrown. a) try block b) call stack trace c) catch block d) interface e) finally block

(E.) (finally block) Every line of a finally block is always executed, even if exceptions are thrown and caught.

Black-box testing uses the internal structure and implementation of the code to be tested in designing the tests.

False Black-box testing treats the code being tested as a black box that cannot be opened or examined. Tests are developed based on possible inputs and expected outputs. Black-box testing does not use knowledge of the internal design or the structure of the code.

A break point is a statement in a program that causes the program to crash.

False A breakpoint is a statement in a program that is marked for use by a debugger. When a program is running under the control of a debugger, execution will pause when a breakpoint is encountered. When paused, the contents of variables can be examined. Program execution can then be resumed in one of several ways: run until the program completes, run until the next breakpoint, run a single statement, etc.

An abstract class must contain abstract methods.

False A class declared as abstract may or may not contain abstract methods.

Let Animal be an interface. Then it is possible to create an object by instantiating the Animal interface.

False An interface cannot be instantiated.

Inheritance should not be considered in the software design process.

False Inheritance should be carefully considered in the software design process. Software systems designed carefully using inheritance can be more flexible than software designed without considering inheritance.

Java supports multiple inheritance.

False Java does not support true multiple inheritance, but it is possible to get some of the features of multiple inheritance using interfaces.

A parent class object must be created before objects of a child class can be created.

False Objects can be created from concrete classes at any point of an inheritance hierarchy in any order.

A variable can always be referenced anywhere in a program.

False Scope rules, based on a variable's declaration, determine where it can be referenced.

It makes sense to declare most abstract classes as final.

False Since an abstract class cannot be instantiated, it makes no sense to declare it as final. It is usually expected that an abstract class will be extended.

The compareTo method of the Comparable interface returns a boolean value.

False The compareTo method returns an integer.


संबंधित स्टडी सेट्स

Unit Test- Age of Reason Short Answer

View Set