[ Quiz Answers | Chapter Index | Main Index ]

Quiz on Chapter 8

This page contains questions on Chapter 8 of Introduction to Programming Using Java. You should be able to answer these questions after studying that chapter. Sample answers to these questions can be found here.

Question 1:

Why do programming languages require that variables be declared before they are used? What does this have to do with correctness and robustness?

Question 2:

What is a precondition? Give an example.

Question 3:

Explain how preconditions can be used as an aid in writing correct programs.

Question 4:

Find a useful loop invariant for the while loop in the binary search algorithm (Subsection 7.4.1).

Question 5:

Java has a predefined class called Throwable. What does this class represent? Why does it exist?

Question 6:

Write a method that prints out a 3N+1 sequence starting from a given integer, N. The starting value should be a parameter to the method. If the parameter is less than or equal to zero, throw an IllegalArgumentException. If the number in the sequence becomes too large to be represented as a value of type int, throw an ArithmeticException.

Question 7:

Rewrite the method from the previous question, using assert statements instead of exceptions to check for errors. What is the difference between the two versions of the method when the program is run?

Question 8:

Some classes of exceptions are checked exceptions that require mandatory exception handling. Explain what this means.

Question 9:

Consider a subroutine processData() that has the header

static void processData() throws IOException

Write a try..catch statement that calls this subroutine and prints an error message if an IOException occurs.

Question 10:

Why should a subroutine throw an exception when it encounters an error? Why not just terminate the program?

Question 11:

Suppose that you have a choice of two algorithms that perform the same task. One has average-case run time that is Θ(n2) while the run time of the second algorithm has an average-case run time that is Θ(n*log(n)). Suppose that you need to process an input of size n = 100. Which algorithm would you choose? Can you be certain that you are choosing the fastest algorithm for the input that you intend to process?

Question 12:

Analyze the run time of the following algorithm. That is, find a function f(n) such that the run time of the algorithm is O(f(n)) or, better, Θ(f(n)). Assume that A is an array of integers, and use the length of the array as the input size, n.

int total = 0;
for (int i = 0; i < A.length; i++) {
   if (A[i] > 0)
      total = total + A[i];
}

[ Quiz Answers | Chapter Index | Main Index ]