Self-assessment 02: Sample questions

The self-assessment will have about three questions. Each involves material that should be familiar from COMPSCI 121, AP CS, or the equivalent.


In the first question, you will read some code and write a concise, high-level, English description of the code’s action. For example:

public static List<Integer> mystery(List<Integer> l, int i) {
  List<Integer> r = new ArrayList<>();
  for (int j = i; j < l.size(); j++) {
    r.add(l.get(j));
  }
  return r;
}

In the second question, you’ll identify a logic error in a short snippet of code. That is, you will find a conceptual error, not an error that the compiler would catch. Here is an example:

/** 
  * Swaps the `i`th and `j`th elements of the List `l`. 
  * Assume 0 <= i <= j <= l.size().   
  */
public static void swap(List<Integer> l, int i, int j) {
  l.set(i, l.get(j));
  l.set(j, l.get(i));
}

In the final question, you will write a short class or method according to a textual description, likely involving a List of some sort. For example, a question might state:

Write a method static List<Integer> concatenate(List<Integer> l1, List<Integer> l2). concatenate should return, as a new list, all the elements of l1 followed by all the elements of l2, in the order they appeared. Your code must not modify l1 or l2.

For example, with an input of l1 = [1, 2, 5], l2 = [2, 4, 1], it should return the list [1, 2, 5, 2, 4, 1].

Assume List and ArrayList are correctly imported.

Check your answers here.