Study questions

Course links

External links

May 6, 2008

(in preparation)

May 5, 2008

(in preparation)

May 2, 2008

(in preparation)

April 30, 2008

(in preparation)

April 29, 2008

(in preparation)

April 28, 2008

(in preparation)

April 25, 2008

  1. What would happen if one started with an empty hash table and inserted a large number of items that, through coincidence or design, all produce the same value when the hash function is applied to them? How would you go about finding a large number of strings s such that hash(s, 100003) has the same value for each?
  2. An implementation of java.lang.String has to override the hashCode method so that it returns equal hash codes for equal strings (even if they are stored in different locations). Find out how the OpenJDK programmers implemented hashCode. Would this be a suitable basis for a hash function in an implementation of hash tables? What further operations would one have to perform on the result of hashCode?

April 23, 2008

  1. In section 19.2 of the text, Weiss implements an algorithm for finding the kth smallest element in a binary search tree. In his implementation, the indices are "one-based," so that the permissible values for k range from 1 to the number of elements in the tree. This is kind of inconsistent with Java's usual practice of "zero-based" indexing (as in arrays, strings, etc.), where the permissible values of an index range from 0 to one less than the number of elements in the structure. Modify the code that Weiss gives in Figure 19.15 so that the argument k of the findKth method is interpreted as a zero-based index.
  2. Write a static Java method that takes a binary search tree as its argument and returns its internal path length, as defined at the bottom of page 645 of the text.

April 22, 2008

(in preparation)

April 21, 2008

(in preparation)

April 18, 2008

(in preparation)

April 16, 2008

  1. Do the first part ("Using a stack of unmated left parentheses') of the lab on parsing parenthesized expressions and submit your code and test runs.
  2. A stack isn't really necessary for this particular task; all you need is an int variable that counts unmated left parentheses. Start the counter at 0 and traverse the given string from left to right. Add 1 to the counter every time you come to a left parenthesis; subtract 1 from it every time you come to a right parenthesis. The string is correctly nested and balanced if, and only if, the counter is zero at the end of the traversal and has never had a negative value at any point along the way. Revise your code so that it uses this approach.
  3. There is an obvious relationship between the value of the counter in the preceding exercise and the state of the stack in the original lab implementation. What is it?

April 15, 2008

  1. It is possible to implement a queue with two stacks, incoming and outgoing. Both stacks start out empty (representing an empty queue). To enqueue an item, we push it onto the incoming stack. Whenever we need to perform any operation involving the front of the queue, we first check whether the outgoing stack is empty; if it is, we repeatedly pop elements from the incoming stack and push them onto the outgoing stack, until the incoming stack is empty. Then we proceed with the operation: To dequeue an item, we pop it from the outgoing stack, and to inspect an item without removing it from the queue, we examine the item at the top of the outgoing stack. The queue is empty if, and only if, both stacks are empty. Write a Java implementation of queues based on this idea.
  2. What is the worst-case running time of an enqueuing operation in the implementation you wrote for the preceding exercise? What is the worst-case running time of a dequeuing operation? What are the average-case running times of these operations?

April 14, 2008

  1. Revise Weiss's printList method on page 572 so that it prints out the contents of the list with an open-bracket at the beginning, a close-bracket at the end, and a comma and a space between each pair of adjacent elements. Your procedure should not print an extra space in front of the close-parenthesis.
  2. Weiss observes on page 573 that a singly-linked list structure cannot efficiently support an operation that returns the last element of a non-empty list. Write a last method that performs this operation on a singly-linked list and determine the order of its running-time function. Why is this unsatisfactory?
  3. Weiss's implementation of the LinkedList data type (in section 17.5) implements his simplified Queue interface from page 229, but not the full java.util.Queue interface. How would one have to change it in order to get it to implement java.util.Queue?

April 11, 2008

  1. Explain the difference between an inner class and a nested class. Using this explanation, go on to explain why a nested class can provide static methods, while an inner class cannot.
  2. Suppose that we create an object of the ArrayList class that Weiss provides in Figures 15.13 through 15.16 and then add sixty elements to it without removing any. How large will the underlying array stored in the theItems field of the ArrayList be at that point?
  3. Describe the order of the running-time functions for the remove procedure in lines 93 through 101 of Figure 15.14 in the text.
  4. In his ArrayStack class, Weiss uses a topOfStack field to keep track of the position in the underlying array occupied by the most recently pushed element of the stack. An alternative design would eliminate topOfStack in favor of a size field that keeps track of the number of items currently in the stack. How would you have to change the implementation of the ArrayStack method to accommodate this alternate design? (Hint: Examine each reference to the topOfStack field.)

April 9, 2008

  1. Using one call to java.lang.Math.random(), write a Java expression for a randomly selected capital letter of the English alphabet. (Hint: the integer value of the capital letter 'A' is 65 and the integer value of the capital letter 'Z' is 90.)
  2. Write a static method that takes a non-negative integer size as argument and returns an array containing the integers from 0 up to and including size - 1, in a random order. (All arrangements of the integers should be equally probable.)
  3. Test the java.util.Random.nextInt() method by using it to generate 100000 pairs of values and counting how many of them are even-even, how many are even-odd, how many are odd-even, and how many are odd-odd. There should be roughly the same number of pairs in each category, although it would also be suspicious if each group had exactly 25000 pairs.

April 8, 2008

  1. Write up and submit the Extras at the end of the lab on sorting.
  2. Write a second version of the priorityQueueSort method that takes a second argument, a Comparator for values of some class that is a superclass of AnyType, and uses that Comparator to compare elements of the given array when sorting them.

April 7, 2008

  1. Write up and submit the lab on sorting (not including the Extras).
  2. Since we haven't studied how priority queues might be implemented, it's difficult to say whether the running time of priorityQueueSort is sensitive to the ordering of the original data. Run some tests in which priorityQueueSort is applied to an array that is already in ascending order, and some in which it is applied to an array that is initially in reverse order. Are the running times comparable to each other and to the method's running times on randomly ordered arrays?

April 4, 2008

  1. Quicksort works best when the partitioning step results in two subarrays of equal size. We could ensure this desirable division by choosing the pivot at each step to be the median of the values in the subarray to be sorted. Why don't real-world implementations of quicksort do this?
  2. How would you adapt the quicksort algorithm so that it takes an additional integer parameter, ranked, and guarantees only that the first ranked positions of the resulting array contain the correctly sorted values (i.e., that they are the ranked smallest values in the array, in ascending order)?
  3. What will the OpenJDK java.util.Arrays.sort1 method that we looked at in class do if it is asked to sort an array in which all of the values are equal? What will be the general order of its running-time function in this case?

April 2, 2008

  1. Since mergesort is a recursive algorithm, one might expect it to run out of space for activation records when it has to sort a very large array. Why isn't this a problem, in practice?
  2. Suppose that you have a randomly ordered pile of 1100 schedule-of-courses cards, one for each student who is preregistering for the fall semester, and you are asked to arrange them in alphabetical order by student name (surname first). What method would you use? Justify your answer.

April 1, 2008

  1. In the insertionSort method in Figure 8.2 of our textbook, why doesn't the evaluation of the expression a[j - 1] through an ArrayIndexOutOfBoundsException when the value of j is 0?
  2. As Weiss notes, the "lower-bound proof" of Theorem 8.2 applies not only to insertionSort but also to several other sorting algorithms. It doesn't apply to the Shell sort, however. Why not?
  3. Does the "lower-bound proof" apply to the selectionSort algorithm demonstrated in class?

March 31, 2008

  1. For every natural number n, the sum of the powers of first n powers of two, from 20 up to and including 2n - 1, is 2n - 1. Prove this by mathematical induction, taking 1 as the base case.
  2. In Figure 7.6 of our textbook, Weiss presents an inefficient algorithm for computing a specified term of the Fibonacci sequence. Retaining the same interface, but using helper functions as appropriate, write two more efficient versions, one using (single) recursion, the other using iteration.
  3. Suppose that we invoke the drawRuler method in Figure 7.13 of our textbook, giving level the value 20. What is the greatest number of activation records for drawRuler calls that will ever be on the stack simultaneously? Is there any possibility that we'll run out of space for those activation records?

March 14, 2008

  1. What is the difference between a priority queue and a queue?
  2. When a PriorityQueue is constructed, if the class to which its elements belong doesn't implement the Comparable interface, the programmer must supply a Comparator object as an argument to the constructor. Why?
  3. Write a Java program that reads in any number of lines from a file and writes them to standard output in lexicographical order. If the file contains duplicate lines, the output should include all of the duplicates.

March 12, 2008

  1. Complete and submit the second Extra in the lab on Iowa demographics.
  2. Extend your solution to the preceding Extra so that the program also constructs a TreeSet<String> containing the names of the Iowa counties that are less densely populated than the state as a whole.
  3. Classes that override the equals method should also override the hashCode method. Why?

March 11, 2008

  1. Complete and submit the lab on Iowa demographics, not including any of the Extras.
  2. What changes would you make in the program you wrote for the lab in order to have it use an ArrayList instead of a LinkedList?

March 10, 2008

  1. When one is traversing a large ArrayList, it doesn't make much difference whether one writes
    for (int index = 0; index < ls.size(); index++)
        ls.get(index).doSomething();
    
    or
    for (Whatever element : ls)
        element.doSomething();
    
    However, when one is traversing a large LinkedList, the second version can be much, much faster. Why?
  2. Write a generic MyStack class that implements the "stack protocol" shown in Figure 6.21 of our textbook.

March 7, 2008

  1. A class that implements the Collection interface must implement the remove method. Yet the objects of some classes that implement Collection are "immutable" -- their sizes and constants can't change. How can the remove method operate on an immutable collection?
  2. The add method in the Collection interface returns a Boolean value -- true if the operation succeeds, false if it does not. Could an add operation on a mutable collection ever fail? How?
  3. In a main method, let switchBoard be a variable of type Collection<Switch>, where Switch is the toggle-switch class that we defined earlier in the semester. Write a loop that turns off all of the switches in the collection that is the current value of switchBoard.

March 5, 2008

  1. Could two iterators for the same data structure exist simultaneously? If so, could they have different "current positions," or would advancing one (by calling its next method) have the side effect of advancing the other? Justify your answers.
  2. Using the MyContainer and MyContainerIterator classes and the Iterator interface from section 6.2.2 of the textbook, write a sequence of Java statements that stores into a BigInteger variable total the sum of the elements of a MyContainer called seq. You may assume that every element of seq is a BigInteger.
  3. Repeat the previous exercise, using the generic versions of MyContainer, MyContainerIterator, and Iterator from /home/stone/courses/java/examples.

March 4, 2008

  1. Submit the completed lab on Swing, including the first of the Extras.
  2. Why do we create, initialize, and position all of the components of the interface before calling the setVisible method to make the window appear on screen?

March 3, 2008

  1. In the introductory lab on Swing, we used a JLabel to display the current value of the counter field in a tallier. Why is this preferable to using a JTextField?
  2. How do you associate an ActionListener with a particular JButton in a graphical user interface?
  3. In the VisibleTallier that we developed in the lab, the buttons are placed at the top of the interface. What would we change to place them at the bottom instead?

February 29, 2008

  1. How is the Swing package (javax.swing) related to the Abstract Widget Toolkit (java.awt)?
  2. What is the purpose of an object of the JFrame class?
  3. What methods must a class define in order to implement the ActionListener interface?

February 27, 2008

  1. Consider the following method, which determines whether all of the elements of a given array of objects are null references:
    public static boolean isAllNulls(Object[] arr) {
        for (Object element: arr)
            if (element != null)
                return false;
        return true;
    }
    
    What is the order of the function that describes its running time? Is the "lower bound" order the same as the "upper bound" order?
  2. What is the order of the function that describes the running time of the following method? (The method prints out all right triangles with integer sides of lengths less than or equal to maxSide.)
    public static void rightTriangles(int maxSide) {
        for (int hypotenuse = 3; hypotenuse <= maxSide; hypotenuse++)
           for (int longLeg = 2; longLeg < hypotenuse; longLeg++)
               for (int shortLeg = 1; shortLeg < longLeg; shortLeg++)
                   if (shortLeg * shortLeg + longLeg * longLeg ==
                       hypotenuse * hypotenuse)
                       System.out.println(shortLeg + "-" + longLeg + "-" +
                                          hypotenuse);
    }
    
  3. Are there any running-time functions that are not of any polynomial order (that is, are not O(nk) for any positive integer k)? If so, given an example.

February 26, 2008

  1. What is the binary logarithm of 65536?
  2. Suppose that the running time in nanoseconds, of a method that determines the kth largest element in an array of n integers is given by the function 35112n2 + 76801n + 168894. Prove that this running-time function is of quadratic order, O(n2).
  3. Complete and submit the lab on timing.

February 25, 2008

  1. What is autoboxing? Under what circumstances is this operation performed by a Java program?
  2. The GenericMemoryCell class shown in Figure 4.28 of the textbook allows us to create a memory cell that will store, say, a Fraction and nothing else, by writing new GenericMemoryCell<Fraction>, or a Shape and nothing else, by writing new GenericMemoryCell<Shape>. Suppose, though, that we want to write a method that takes a memory cell as a parameter, but only if it is a memory cell that is either specified to hold a Shape or specified to hold an object of some class that extends Shape. In defining that method, how would we write the type for the parameter?
  3. Write a generic static method called copyArray that takes two parameters, each of which must be an array of values of some non-primitive type, and copies the elements of the first into the second (overwriting the values previously stored in the second array). The method should check to make sure that the two arrays have the same length (throwing an exception if they are not) and should also ensure that the type of the elements of the source array is the same as, or a subtype of, the type of the elements of the target array.
  4. Define an IntFunction interface containing a single (abstract) method, operateOn, that takes one int parameter and returns an int value. Define a SquareFunction class that implements this interface; it should implement operateOn as a function that squares its argument. Similarly, define a SuccessorFunction class that implements operateOn as a function that returns the successor of its argument. Finally, define a Mapper class, with a method map that takes two arguments, an IntFunction func and an array arr of ints, and returns a newly allocated array containing the results of applying func to each argument of arr in turn. Demonstrate these functions by computing the squares of the successors of the elements of the array {-7, 12, 0}.

February 22, 2008 (revised)

  1. Complete the lab on inheritance and abstraction and submit the files you create.
  2. Add a RegularHexagon class to the Shape hierarchy presented in section 4.2 of the textbook, constructing each object of this class from the length of its side.

February 20, 2008

  1. Extend the inheritance hierarchy for geometric shapes presented in section 4.2 of the textbook to include a Triangle class, with a triangle being specified by the lengths of its sides. Hint: If a, b, and c are the lengths of the sides of a triangle, and s is its semiperimeter, then its area is the square root of the product s(s - a)(s - b)(s - c). (Thanks, Heron of Alexandria!)
  2. Why is it impossible to construct an object that belongs to an abstract class (as opposed to any of the classes derived from it)?
  3. What happens if a single class implements two interfaces, each of which includes a method with the same name, number of parameters, and types of parameters, but different return types? Which, if either, of the types should the implementation return?

February 19, 2008

  1. Suppose that class M extends class K. An object of class M is then type-compatible with a local variable, field, or parameter that is declared to be of type K, and can be stored in such a variable, field, or parameter. Is the converse true? Is an object of class K type-compatible with with a local variable, field, or parameter that is declared to be of type M? Justify your answer.
  2. A class M that extends another class K cannot override any public method of K with a private method that has the same signature. Why is this not permitted?
  3. The designer of any method in a class definition must decide whether or not to declare it final. What considerations would affect this decision? What advantages or disadvantages do final methods have?

February 18, 2008

  1. Describe a situation in which you might want two or more launch configurations for the same program when developing and testing code in Eclipse.
  2. Add to the CoinBox class that you developed in today's lab a method for releasing a quarter. What should this method do if the CoinBox to which the message is sent contains no quarters?
  3. Your current code probably assumes that a CoinBox can contain as many as 2147483647 coins of each type. Impose a more realistic limit, say 480. What should your deposit methods do if the CoinBox is full and can't receive any more coins?

February 15, 2008

  1. What are the advantages and disadvantages of a programming development environment, such as Eclipse or DrScheme, in comparison to using separate development tools (a shell, an editor, a compiler, etc.)?
  2. Carry out the ``Using Eclipse'' lab and submit the CoinBox.java file that you create.

February 13, 2008

  1. Suppose that the file containing the definition of class A imports class B, and the file containing the definition of class B imports class C. Can the definition of class A then contain "shorthand" references to class C? Justify your answer.
  2. Why can we import only static members of other classes?
  3. From what classes can a field that is declared without any access modifier be accessed?
  4. Why are local variables declared without access modifiers?

February 12, 2008

  1. Why is the code for raising an exception when the proposed denominator is zero, ensuring that the denominator is non-negative, and reducing the fraction to lowest terms present in only one of the two Fraction constructors?
  2. Add static final fields ZERO and ONE to the Fraction class, initializing them to the fractions 0/1 and 1/1, respectively.
  3. Add a compareTo method to the definition of the Fraction class. It should take one argument, a fraction, and return a negative int value if the fraction that receives the compareTo message is less than the argument, a positive int value if the argument is less than the fraction that receives the message, and the int 0 if the two fractions are equal.
  4. Add a pow method to the definition of the Fraction class. It should take one argument, an int, and return the result of raising the fraction that receives the pow message to the specified power. (Consider carefully what should happen if the argument is zero or negative.)

February 11, 2008

  1. What is the effect of the -private command-line argument to the javadoc program?
  2. How can you arrange to have the javadoc program include author and version information in the Web documents that it constructs?
  3. What does the @param tag in a documentation comment do?
  4. Complete and submit parts 4 and 5 of the lab on rational numbers.

February 8, 2008

  1. Complete and submit parts 1-3 of the lab on rational numbers.
  2. Supply a third Fraction constructor that takes as arguments strings that represent the intended numerator and denominator.
  3. Supply a fourth Fraction constructor that takes a single argument n of type int and constructs the Fraction n/1.

February 6, 2008

  1. Why might a class have two or more different constructors?
  2. It is possible to send the toString message to an object of the Switch class that we defined in class. Write a program that prints out the string that is returned as the representation of a Switch. Explain where the definition of the toString method that is being executed would be found.
  3. Why can static methods invoke other methods only if they are also static? Why can static methods refer to fields only if they are also static?
  4. Write and test the definition of a class that contains two private fields, car and cdr, each capable of storing an integer. Write a two-argument constructor for this class, and provide an accessor and a mutator for each field.

February 5, 2008

  1. Does Java have a built-in method for computing square roots? How does one invoke it? What class is it defined in? What package is it in? Must the package be imported in any class that contains an invocation of the method?
  2. How do you find out what package a given class -- StringTokenizer, say -- belongs to?
  3. It is quite common for a Java program that interacts with the user through a terminal window to include a declaration essentially similar to
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    
    Why is it advantageous to construct separate InputStreamReader and BufferedReader objects instead of simply using the read method of System.in itself?
  4. Explain the difference between System.out and System.err.
  5. In the program shown in Figure 2.16 on page 56 of our textbook, what happens if the main method receives two or more command-line arguments?

February 4, 2008

  1. In Java, what will happen if a method attempts to store a value into an array at a position that is greater than or equal to the array's length?
  2. Explain the difference between checked and unchecked exceptions.
  3. Is it valid, in Java, to write a try-statement that catches an unchecked exception?
  4. In the program in Figure 2.11 on page 49 of our textbook, which method call(s) could throw an IOException? Which could throw a NumberFormatException? How would you find out what exceptions, if any, a particular method can throw?

February 1, 2008

  1. To compute the number of characters in a string stored in the variable foo, one writes foo.length(). To compute the number of elements in an array stored in the variable bar, one writes bar.length. Why are the parentheses required in the former case and prohibited in the latter?
  2. Suppose that vec and total are two local variables in a method, declared thus:
    int[] vec = new int[256];
    int total;
    
    Suppose further that the statements immediately following these declarations assign values to all of the elements of vec, perhaps by filling them up with random numbers, as in Figure 2.4 on page 39 of our textbook. Write further statements that would then compute the sum of the elements of vec, storing that sum in total.
  3. If, in the preceding exercise, you didn't use an enhanced for-loop, write a solution that does.
  4. Write a Java program that takes one or more command-line arguments, each of which is a numeral, and returns the average (arithmetic mean) of the numbers they denote. (The numerals will come in as strings; you'll have to parse out their values as doubles before you can do arithmetic on them.)

January 30, 2008

  1. Complete parts 1-4 of the ``Experiments on strings'' lab and submit the final version of the StringExperiments class.
  2. Write a Java statement that prints out all of the non-null substrings of the string "therein". (Hint: Use nested for-statements.)

January 29, 2008

  1. In Java, it is valid to assign a null reference to a variable of some type that can hold objects, but it is not valid to apply the field selection operator . to a null reference. Why?
  2. When the == operator appears between two variables of the same non-primitive type, does it test whether the references stored in the variables are identical or whether the objects referred to are equivalent? What difference does it make?
  3. In the SwitchTester class that we developed today, how would the output change if we added the statement vacuumCleaner = lamp; at the beginning of the main method? Explain the differences.

January 28, 2008

  1. In Java, as section 1.6 of our text explains, a method that is invoked can return a value, but it is also possible to define methods (the ones that have the keyword void in place of a return type) that do not return values at all. Why would one ever define such a method? Of what use could calling it possibly be, if the object to which it belongs doesn't respond to the message?
  2. What does the keyword static mean when it modifies a method declaration? What does it mean when it modifies a field declaration?
  3. What does the keyword final mean when it modifies a field declaration? What will happen if a program violates the restriction that the final keyword tries to impose?

January 25, 2008

  1. In section 1.5.4 of our text, Weiss says that the body of a while-loop "generally does something that can potentially alter the value of expression [the entry test]; otherwise, the loop could be infinite." What is an infinite loop? Give an example of a Java while-statement that would loop infinitely if executed. How would such a loop manifest itself to the user of a program that included it?
  2. Recall that the side effect of the extended assignment expression pow *= 2 is to replace the previous value of the variable pow with its double. Using this knowledge, write a for-loop that would print out the powers of 2 from 1 up to and including 1024.
  3. In section 1.5.7 of our text, while discussing the continue statement, Weiss observes that his example
        for (int i = 1; i <= 100; i++) {
            if (i % 10 == 0)
                continue;
            System.out.println(i);
        }
    
    could be rewritten in other, equivalent ways. Suggest a way to get exactly the same effect -- printing the positive integers up to 100, except those that are multiples of 10 -- without using continue.
  4. In Figure 1.5 (page 18), what difference, if any, would it make if we omitted the break-statement in line 13?

January 23, 2008

  1. What is the difference between a conditional expression (as described in section 1.5.9 of our text) and an if-statement?
  2. Write an if-statement that sets the int variable speed to the absolute value of the value of the int variable velocity.
  3. Write an if-statement that prints out the string "large positive" if the current value of the double variable signand is greater than one billion, "large negative" if it is less than minus one billion, and "small" otherwise.

January 22, 2008

  1. What is the difference between a value of type float and a value of type double?
  2. When the unary operator ++ is written in front of a variable, what is its effect?
  3. What is the difference between the & and && operators, when their operands are Boolean expressions?
  4. Adapt the following Java program so that it prints out the product of 2897 and -71682. appropriately labelled. Compile and run the adapted program. Check the answer.
    /* Summer: Computing the value of an arithmetic expression.
    
       John David Stone
       Department of Computer Science
       Grinnell College
       stone@cs.grinnell.edu
    
       created January 21, 2008
       last revised January 21, 2008
    
       This program computes and prints out the value of an particular
       arithmetic expression, appropriately labelled.
    */
    
    public class Summer {
      public static void main(String[] ignored) {
        System.out.print("The sum of 5 and 7 is ");
        System.out.print(5 + 7);
        System.out.println(".");
      }
    }
    

January 21, 2008

  1. How does a course dealing with the object-oriented model of computation and problem solving, with emphasis on design and interpretation of data structures, fit into the introductory computer science curriculum at Grinnell?
  2. Describe and assess the analogy between fields and methods of an object, on one hand, and the memory and instruction set of a computer on the other.
  3. What is a shell?
  4. How does a shell find the executable file containing a program that the user has asked it to run?
  5. What are the similarities and differences between values of Java's int type and exact integers in Scheme?