Question 40

Consider the following recursive method:

public static void whatsItDo(String str) {
    int len = str.length();
    if (len > 1) {
        String temp = str.substring(0, len - 1);
        whatsItDo(temp);
        System.out.println(temp);
    }
}

What is printed as a result of the call whatsItDo ("WATCH") ?

My answer: B Correct answer: C

Explanation: This would be the output if str was printed before the recursive call to whatsItDo(temp); instead of the System.out.println(temp); line which comes after the recursive method call. When the recursive call whatsItDo(temp); is executed, the current sequence of statements are paused. The call whatsItDo(“WATCH”) assigns to temp a substring of “WATCH” starting at 0 and ending at 4 – 1 or 3, which is “WATC”. Next the call whatsItDo(“WATC”) is made. The call whatsItDo(“WATC”), sets its local temp to “WAT” and calls whatsItDo(“WAT”). The call whatsItDo(“WAT”), sets its local temp to “WA” and calls whatsItDo(“WA”). The call whatsItDo(“WA”), sets its local temp to “W” and calls whatsItDo(“W”). The call whatsItDo(“W”) reaches the base case and doesn’t do anything since the length of “W” is 1. Then we need to finish the call to whatsItDo(“WA”), which prints the value of its local temp, “W”. Then we need to finish the call to whatsItDo(“WAT”), which prints the value of its local temp, “WA”. Then we need to finish the call to whatsItDo(“WATC”), which prints the value of its local temp, “WAT”. Then we need to finish the call to whatsItDo(“WATCH”), which prints the value of its local temp, “WATC”. And the recursive calls are complete.

Question 39

Consider the following recursive method:

public int recur(int n) {
    if (n <= 10) {
        return n * 2;
    } else {
        return recur(recur(n / 3));
    }
}

What value is returned as a result of the call recur(27)?

My Answer: E Correct answer: D

Explanation: The value of recur(9) is 18. However, this call was made within another recursive call and is not the final return value. The call recur(27) returns the value of recur(recur(9)) since 27 is greater than 10. The call recur(9) returns 18, since 9 is less than or equal to 10. Therefore, recur(recur(9)) is recur(18). The call recur(18) returns recur(recur(6)) since 18 is greater than 10. The call recur(6) returns 12, since 6 is less than or equal to 10. Therefore, recur(recur(6)) is recur(12). The call recur(12) returns recur(recur(4)) since 12 is greater than 10. The call recur(4) returns 8, since 4 is less than or equal to 10. Therefore, recur(recur(4)) is recur(8). The call recur(8) returns 16, since 8 is less than or equal to 10. Therefore, recur(27)returns the value of 16.

Question 34

Consider the following class declarations:

public class Point {
    private double x; // x-coordinate
    private double y; // y-coordinate

    public Point() {
        x = 0;
        y = 0;
    }

    public Point(double a, double b) {
        x = a;
        y = b;
    }

    // There may be instance variables, constructors, and methods that are not shown.
}

public class Circle {
    private Point center;
    private double radius;

    public Circle(double a, double b, double r) {
        /* missing code */
    }
}

Which of the following replacements for /* missing code */ will correctly implement the Circle constructor?

My answer: D

Correct answer: B

Explanation: Choice III uses the default Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error. Choice I uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0, instead of x assigned the value a and y assigned the value b. Choice II correctly uses the two parameter Point constructor to create a new Point with x assigned the value a and y assigned the value b. Choice III uses the no parameter Point constructor to assign center a new Point with x and y both equal to 0. It attempts to update x and y, however since they are private instance variables in Point, they are not able to be accessed directly in Circle. This code will cause a compile time error.

Question 33

Consider the following code segment.

int sum = 0;
int k = 1;
while (sum < 12 || k < 4) {
    sum += k;
}

System.out.println(sum);

What is printed as a result of executing the code segment?

My answer: C

Correct answer: E

Explanation: This would be correct if the boolean condition was changed from an or (   ) to an and (&&). Since k is never incremented, the or (   ) will always be true since k will always be less than 4 and an infinite loop will occur. Since k is never changed in the body of the while loop, it will always be 1 and less than 4. In a boolean expression with or (   ) if one of the two expressions is true, the expression is true. This will cause an infinite loop.

Question 28

Directions: Select the choice that best fits each statement. The following question(s) refer to the following method:

public static int mystery(int n) {
    int x = 1;
    int y = 1;

    // Point A

    while (n > 2) {
        x = x + y;
    
        // Point B

        y = x - y;
        n--;
    }

    // Point C

    return x;
}

Which of the following is true of method mystery?

My answer: A

Correct answer: E

Explanation: At //Point B, the update x = x + y has already occurred so x will at least be 2, the sum of the initial value of x and y (1 + 1). The while loop only iterates while n is greater than 2 and //Point B is in the body of the while loop prior to any change to the value of n. At this point, n will always be greater than 2.

Question 27

What value is returned as a result of the call mystery (6)?

My answer: E

Correct answer: D

Explanation: This would be the value of x if the loop iterated while n > = 2 instead of n > 2. The method mystery starts by initializing both x and y to the value 1. In the first iteration of the while loop, n (which is 6) is greater than 2. The variable x is assigned 1 + 1 or 2. The variable y is assigned 2 – 1 or 1. The variable n is decremented by 1 and has the value 5. In the second iteration of the while loop, n is greater than 2. The variable x is assigned 2 + 1 or 3. The variable y is assigned 3 – 1 or 2. The variable n is decremented by 1 and has the value 4. In the third iteration of the while loop, n is greater than 2. The variable x is assigned 3 + 2 or 5. The variable y is assigned 5 – 2 or 3. The variable n is decremented by 1 and has the value 3. In the fourth iteration of the while loop, n is greater than 2. The variable x is assigned 5 + 3 or 8. The variable y is assigned 8 – 3 or 5. The variable n is decremented by 1 and has the value 2. At this point the while loop terminates since n is no longer greater than 2 and the value 8 is returned.

Question 25

A rectangular box fits inside another rectangular box if and only if the height, width, and depth of the smaller box are each less than the corresponding values of the larger box. Consider the following three interface declarations that are intended to represent information necessary for rectangular boxes.

public interface RBox {
    double getHeight();

    double getWidth();

    double getDepth();

}

public interface RBox {
    boolean smallerHeight(RBox other);
    
    boolean smallerWidth(RBox other);

    boolean smallerDepth(RBox other);
}

public interface RBox {
    double getSurfaceArea();

    double getVolume();
}

Which of the interfaces, if correctly implemented by a Box class, would be sufficient functionality for a user of the Box class to determine if one Box can fit inside another?

My answer: E

Correct answer: D

Explanation: Please note that interface is no longer a part of the AP CSA exam. Choice III provides the user with the getSurfaceArea and getVolume methods which provide the surface area and volume of a box. Unfortunately, a box with a smaller surface area or volume is not necessarily small enough to fit inside another box with a larger surface area or volume. For example, if box 1 has dimensions 1, 2, 5 and box 2 has dimensions 2, 3, 4. Box 1 has a surface area of 34 units squared and a volume of 10 units cubed. Box 2 has a larger surface area of 52 units squared and a larger volume of 24 units cubed. However, box 1 cannot fit inside box 2 because it has a height of 5 which is greater than any of the dimensions of box 2. A rectangular box fits inside another rectangular box if and only if the height, width, and depth of the smaller box are each less than the corresponding values of the larger box. Choice I provides the user access to the height, width, and depth of a box through the accessor methods getHeight, getWidth, and getDepth. This allows comparisons to be made in each of the three dimensions to determine if one box can fit inside another box. Choice II provides the user with methods smallerHeight, smallerWidth, and smallerDepth that let the user know if one box is smaller than the other in each of the three dimensions. Choice III provides the user with the getSurfaceArea and getVolume methods which provide the surface area and volume of a box. Unfortunately, a box with a smaller surface area or volume is not necessarily small enough to fit inside another box with a larger surface area or volume. For example, if box 1 has dimensions 1, 2, 5 and box 2 has dimensions 2, 3, 4. Box 1 has a surface area of 34 units squared and a volume of 10 units cubed. Box 2 has a larger surface area of 52 units squared and a larger volume of 24 units cubed. However, box 1 cannot fit inside box 2 because it has a height of 5 which is greater than any of the dimensions of box 2.

Question 23

Consider the following instance variable and method.

private List<String> animals;

public void manipulate() {
    for (int k = animals.size() - 1; k > 0; k--) {
        if (animals.get(k).substring(0, 1).equals("b")) {
            animals.add(animals.size() - k, animals.remove(k));
        }
    }
}

Assume that animals has been instantiated and initialized with the following contents.

{"bear", "zebra", "bass", "cat", "koala", "baboon"};

What will the contents of animals be as a result of calling manipulate?

My answer: E

Correct answer: B

Explanation: List is an interface, which an ArrayList implements. Please note that List is no longer tested as part of the AP CSA exam and ArrayList will be used instead. This would be the result if when words that started with “b” were found, they were added to the end instead of inserted at index animals.size() – k such as if the statement in the for loop was animals.add(animals.remove(k));. The manipulate method contains a for loop with a loop control variable k that starts at the right most index of animals, decrements by 1 each time, until k is equal to 0. In the first iteration, when k is 5, if the element of animals at 5 (“baboon”) starts with a “b”, which it does, then this value is removed from the list and inserted at index 1. The list would then be {“bear”, “baboon”, “zebra”, “bass”, “cat”, “koala”}. In the second iteration, when k is 4, the element of animals at 4 (“cat”) does not start with a “b” and no changes are made to the list. In the third iteration, when k is 3, the element of animals at 3 (“bass”) starts with a “b”. This value is removed from the list and inserted at index 3. Since it was already at index 3, the list would not change. In the fourth iteration, when k is 2, the element of animals at 2 (“zebra”) does not start with a “b” and no changes are made to the list. In the fifth iteration, when k is 1, the element of animals at 1 (“baboon”) starts with a “b”. It is removed from the list and inserted at index 5. The list would then be {“bear”, “zebra”, “bass”, “cat”, “koala”, “baboon”}. Finally, k decrements to 0 which is not greater than 0 so the loop terminates.

Question 21

Consider the following method, which is intended to return the element of a 2-dimensional array that is closest in value to a specified number, val.

public double findClosest(double[][] mat, double val) {
    double answer = mat[0][0];
    double minDiff = Math.abs(answer - val);
    for (double[] row : mat) {
        for (double num : row) {
            if (/* missing code */) {
                answer = num;
                minDiff = Math.abs(num - val);
            }
        }
    }
    return answer;
}

Which of the following could be used to replace / * missing code * / so that findClosest will work as intended?

My answer: B

Correct answer: D

Explanation: To find the value that is closet to val, the algorithm needs to calculate the positive difference between num and val. The algorithm uses nested enhanced for loops to iterate across all the elements in mat. The variable num is assigned the value of each element. If the positive difference between num and val is less than minDiff, num is the element of mat that is closest to val so far.

Question 20

Consider the following method:

public static void arrayMethod(int nums[]) {
    int j = 0;
    int k = nums.length - 1;

    while (j < k) {
        int x = nums[j];
        nums[j] = nums[k];
        nums[k] = x;
        j++;
        k--;
    }
}

Which of the following describes what the method arrayMethod() does to the array nums?

My answer: B

Correct answer: E

Explanation: Since j is incremented, the first element is only used in the first iteration of the while loop. This method uses a swapping algorithm to swap elements in nums. The variable j starts with the value 0, which is the index of the left most element in nums. The variable k starts with the value nums.length – 1, which is the index of the right most element in nums. As long as j is less than k, x is assigned the value of nums[j], this ensures that the value of nums[j] is not lost when nums[j] is assigned the value of nums[k]. Then nums[k] is assigned the value of x. This algorithm swaps the values of nums[j] and nums[k]. Then j is incremented and k is decremented, ensuring that the contents of the array nums are reversed at the conclusion of the arrayMethod method.

Question 19

Assume that a and b have been defined and initialized as int values. The expression

!(!(a != b ) && (b > 7))

is equivalent to which of the following?

My answer: C

Correct Answer: B

Explanation: The opposite of !(a != b) is just (a != b). De Morgan’s Law states that !(p && q) is equivalent to !p   !q. By applying De Morgan’s Law to this expression, we negate the first expression !(!(a !=b)) and the second expression !(b >7) to form !(!(a != b))   !(b > 7). In the first expression the two consecutive not operators (!) cancel each other out giving us (a != b). In the second expression, the opposite of > is <= giving us (b <= 7). The equivalent expression is (a != b)   (b <= 7).

Question 18

Assume that myList is an ArrayList that has been correctly constructed and populated with objects. Which of the following expressions produces a valid random index for myList?

My answer: A

Correct answer: B

Explanation: The indices for myList are 0 through myList.size() – 1, for a total of myList.size() elements. Using this statement will result in a range between -1 and myList.size() – 2. The indices for myList are 0 through myList.size() – 1, for a total of myList.size() elements. Using Math.random()generates a random floating point number between 0 and 1, not including 1. When this value is multiplied by the number of elements we want in our range, myList.size(), a random floating point number between 0 and myList.size(), not including myList.size(), is generated. When this value is typecast as an int, the result is an integer value between 0 and myList.size() – 1 inclusive.

Question 17

Consider the following code segment:

int[] arr = {1, 2, 3, 4, 5, 6, 7};

for (int k = 3; k < arr.length - 1; k++) {
    arr[k] = arr[k + 1];
}

Which of the following represents the contents of arr as a result of executing the code segment?

My answer: B

Correct answer: C

Explanation: The size of the array is immutable. When the assignment statement is executed, no values are removed, but copied to the element to the left. The for loop control variable k starts with the value 3, is incremented by 1 and terminates the loop when its value is arr.length – 1. In the first iteration, when k is 3, arr[3] is assigned the value arr[4]. The contents of the arr have been updated to {1, 2, 3, 5, 5, 6, 7}. In the second iteration, when k is 4, arr[4] is assigned the value arr[5]. The contents of arr have been updated to {1, 2, 3, 5, 6, 6, 7}. In the third iteration, when k is 5, arr[5] is assigned the value arr[6]. The contents of arr have been updated to {1, 2, 3, 5, 6, 7, 7}. Then k is incremented to 6 and the loop terminates.

Question 12

Consider the following method.

public String mystery(String input) {
    String output == "";

    for (int k = 1; k < input.length(); k = k + 2) {
        output += input.substring(k, k + 1);
    }

    return output;
}

What is returned as a result of the call mystery(“computer”) ?

My answer: D

Correct answer: C

Explanation: This would be the return value if k was incremented by 1 instead of 2 and the loop condition was changed to k < input.length()- 1. The value of the loop control variable k starts at 1 and is incremented by 2 as long as it is less than input.length. In this case, input is assigned “computer”, so input.length is 8. The values of k are 1, 3, 5, 7, and then when k is 9, the loop terminates. The statement input.substring (k, k + 1) will return the value of input at index k. The values that are added to output in order are “o”, “p”, “t”, and “r”. The value “optr” is returned.

Question 11

Directions: Select the choice that best fits each statement. The following question(s) refer to the following information

Consider the following instance variable and methods. You may assume that data has been initialized with length > 0. The methods are intended to return the index of an array element equal to target, or -1 if no such element exists.

private int[] data;

public int seqSearchRec(int target) {
    return seqSearchRecHelper(target, data.length - 1);
}

private int seqSearchRecHelper(int target, int last) {
    // Line 1

    if (data[last] == target) {
        return last;
    } else {
        return seqSearchRecHelper(target, last - 1);
    }
}

Which of the following should be used to replace // Line 1 in seqSearchRecHelper so that seqSearchRec will work as intended?

My answer: E

Correct answer: B

Explanation: This will cause an infinite loop if data contains more than one element as last will start out greater than or equal to 0 and last is not updated in the loop. The seqSearchRecHelper recursive method does not work as intended when target does not appear in data. In this case, when last becomes -1, the method will throw an ArrayIndexOutOfBoundsException in the first if statement after line 1. To prevent this, we should add a check to see if last is less than 0 and if it is, return -1 as expected.