The College Board released the complete 2009 AP Computer Science A Exam, including the multiple choice section. While their released exam includes detailed explanations for each free response question, it does not offer detailed explanations for each multiple choice question. Question by question explanations for the 2009 AP Computer Science A Multiple Choice Section are below.

You must purchase the released Exam itself from the College Board’s Online Store. Refer to the College Board product for the original questions and for the letter answers.

Review the 2009 AP CS A Exam Multiple Choice with AP CS Tutor Brandon Horn.

If you do not have and cannot get a copy of this, the 2014 AP CS A Course Description has 25 excellent practice multiple choice. The 2014 AP CS A Course Description is available for free on the College Board’s website.

## Question 1

`value`

is unchanged before it is printed the first time, so the first number output is `15`

. `value`

is incremented after the call to `println`

and the loop stops when `value == 28`

so the last number output is `27`

.

## Question 2

Case I: The `&&`

operation evaluates to `true`

if and only if both operands are `true`

. The condition in Case I is evaluated as `(bonusOne && bonusTwo) && bonusThree`

. For the condition to evaluate to `true`

all 3 variables must be `true`

. This correctly implements the intended condition.

Case II: The `||`

operation is `true`

if at least 1 operand is `true`

. The condition in Case II evaluates to `true`

if at least 1 of the variables is `true`

, which is not the intent.

Case III: The conditions are evaluated independently. It is possible for `grade`

to be incremented by 0, 5, 10 or 15 points depending on the values of the variables. This is not the intent.

## Question 3

Interchanging, often called swapping, the values of at 2 positions in an array requires the use of a variable to store the value that would otherwise be lost when one value in the array is replaced with the other.

Answers A and B fail to use a temporary variable. Answer C uses a temporary variable but stores the wrong value. Answer E stores the correct variable but does not use the temporary variable.

Answer D correctly stores one of the values in the temporary variable, overwrites the original copy then retrieves the temporary copy.

## Question 4

The Quick Reference contains documentation for each `ArrayList`

method called. The list after each step is below.

```
[A]
[A, B]
[A, B, C]
[D, A, B, C]
[D, A, B]
[E, D, A, B]
```

## Question 5

A superclass contains fields and methods that are used by all of its subclasses. The term superclass is not intended to imply importance or complexity, but rather indicates that the superclass is above a subclass in a class hierarchy.

Answers B and C incorrectly refer to the complexity of a superclass. Answer D suggests that data should be public, which is not only unnecessary but also violates the principle of encapsulation.

Answer E states that the superclass should provide the most specific details; however, a superclass is actually less specific than its subclasses. The subclass can contain details specific to itself.

## Question 6

If `k`

is initialized to `1`

, the outer loop will never run, so the inner loop will never run, so `"Hello"`

will never be printed.

## Question 7

If `k`

is initialized to `n`

, the outer loop will run `n - 1`

times. (If `p`

was initialized to `1`

, the outer loop would run `n`

times.) Each time the outer loop runs, the inner loop runs `n - 1`

times.

`(n - 1)`

runs of the outer loop multiplied by `(n - 1)`

runs of the inner loop is `(n - 1) * (n - 1)`

or `n - 1`

squared.

## Question 8

Case I uses a regular `for`

loop to traverse `vals`

. `total`

is incremented by `vals[pos]`

during each run of the loop. After the loop `total`

contains the sum of all values in `vals`

, as intended.

Case II attempts to traverse `vals`

backwards, which would work, except `pos`

is initialized to `vals.length`

. `vals.length`

is not a valid index in `vals`

, so the loop throws an `ArrayIndexOutOfBoundsException`

on its first iteration.

Case III uses a `while`

loop to traverse `vals`

. The loop is exactly equivalent to the `for`

loop from Case I, so it works as intended.

## Question 9

The loop runs 5 times. Each value of `rep`

and the `String`

printed are shown below.

```
0: "ab"
1: "bc"
2: "cd"
3: "de"
4: "ef"
```

Everything is printed on the same line, so the output is `abbccddeef`

.

The last call to substring does not go out of bounds. See Strings on the AP CS A Exam for more about each `String`

method.

## Question 10

Tracing the method for 50 iterations of the loop would take too long, so it is important to determine what each variable represents. Each `if`

statement is independent (there are no `else`

statements), so:

`typeA`

is incremented for each value of `k`

that is a multiple of both 2 and 5.

`typeB`

is incremented for each value of `k`

that is a multiple of 2 (regardless of whether it is also a multiple of 5).

`typeC`

is incremented for each value of `k`

that is a multiple of 5 (regardless of whether it is also a multiple of 2).

The loop is run for values of `k`

from `1`

to `50`

, inclusive. Within that range, there are 5 multiples of both 2 and 5, 25 multiples of 2, and 10 multiples of 5. The method outputs `5 25 10`

.

## Question 11

`/* expression */`

should evaluate to `true`

if and only if the value in `nameList`

at position `j`

is equal to `name`

.

`nameList`

is an `ArrayList`

so the element at position `j`

is accessed as `nameList.get(j)`

. The contents of `String`

objects are compared using the `equals`

method, not the `==`

operator.

The correct comparison is `nameList.get(j).equals(name)`

.

See Strings on the AP CS A Exam for more about each `String`

method.

## Question 12

Case I returns `n * 10`

for all values of `n`

that are multiples of both 3 and 4. It returns `n`

for all other values of `n`

.

In the table of example inputs and outputs, `someProcess(3)`

returns `30`

. Case I would return `3`

because 3 is not a multiple of both 3 and 4. Case I will not produce the intended results.

Case II returns `n * 10`

for all values of `n`

that are multiples of either 3 or 4. It returns `n`

for all other values of `n`

.

This corresponds exactly with the table given. Each value of `n`

that is a multiple of either 3 or 4 results in a return value of `n * 10`

. All other values of `n`

result in a return value of `n`

.

Case III is equivalent to Case I. Both conditions must evaluate to `true`

for the method to return `n * 10`

.

## Question 13

When I see a `print`

statement in a recursive method on an Exam, I get excited. `print`

statements often make recursion problems way easier to solve.

See Recursive methods with print statements for an explanation of the approach.

Answer choice (E) mentions infinite recursion. My preference is to handle that answer choice first. To determine if the method call `mystery(123456)`

results in infinite recursion, consider the base case and the recursive call.

The recursive call is inside an `if`

statement so the base case is the opposite of the condition. The base case is `x / 10 == 0`

. `x / 10`

removes the last (rightmost) digit of `x`

. The base case is when a digit is removed and the result is `0`

.

The recursive call is `mystery(x / 10)`

. The method is called with `x`

without its last digit.

`mystery`

contains a `print`

statement that prints `x % 10`

, the last (rightmost) digit of `x`

. The `print`

statement is after the recursive call. The value of `x`

is not changed within `mystery`

.

The last value that will ever be printed is `6`

. Answer choices (A), (B), and (C) print `6`

last. The initial call to `mystery`

is with a 6 digit number. Each recursive call removes a single digit. Each all to the method prints a digit. More than 2 digits will be printed, so the answer must be (C).

This question is not an exception. It is very common for questions that include recursive methods with `print`

statements to be easily solved by considering the position of the `print`

statement(s) relative to the recursive call(s).

It is also possible to trace this method, though I would not do so on the Exam. A stack based trace of #13 is available as a demonstration of the technique.

## Question 14

Case I attempts to calculate the value for `yrs`

as `extraMonths % 12`

and the value for `mos`

as `extraMonths / 12`

. There are 2 issues with this approach. The assignments are reversed. There are `extraMonths / 12`

additional years and `extraMonths % 12`

additional months. Case I also fails to take into account the situation in which `months + mos`

exceeds 12.

Case II correctly converts the original age into months as `years * 12 + months`

. It then adds `extraMonths`

to correctly calculate the new age in months. Case II then converts the total number of months into years (`totalMonths / 12`

) and months (`totalMonths % 12`

) and assigns the results to `years`

and `months`

. Case II works as intended.

Case III first computes the total number of months, including the new months as `months + extraMonths`

. Case III correctly determines how many years are represented by those months as `totalMonths / 12`

and correctly adds the result to `years`

. The total number of months is what remains after converting all groups of 12 months to years, `totalMonths % 12`

. Case III correctly assigns this to `months`

. Case III works as intended.

## Question 15

`inRangeMessage`

returns `"Not in range"`

if either part of the condition is `true`

; otherwise, it returns `"In range"`

. In other words, `inRangeMessage`

returns `"In range"`

if and only if `value >= 0 && value <= 100`

.

Case I incorrectly returns `"In range"`

if `value >= 0`

without checking whether `value <= 100`

.

Case II checks each out of range condition separately and returns `"Not in range"`

if either condition is `true`

. If neither condition is `true`

, it correctly returns `"In range"`

. Case II works as intended.

Case III has the same problem as Case I. Case III immediately returns `"In range"`

if `value >= 0`

without checking the upper bound.

## Question 16

After the 3 assignment statements, `one`

and `three`

store the memory address of the same object/instance of `SomeClass`

. (They both point to the same object.) `two`

points to a different object. The statement `one.increment(200)`

increments the value of `num`

in the object to which both `one`

and `three`

point. The object to which `two`

points is unaffected.

Immediately prior to the `println`

statement, `one`

and `three`

point to the same object containing `num`

with value `300`

. `two`

points to a different object containing `num`

with value `100`

.

See Primitive types vs references exercises for additional details of how references work and how to draw memory diagrams for problems such as #16.

## Question 17

`sortArray`

implements a variant of selection sort that sorts the array starting from the end. `/* missing code */`

controls the inner loop, which is responsible for finding the maximum value in the unchecked part (from `0`

to `j`

). `pos`

starts at `j`

, so the inner loop only needs to traverse the elements from `0`

to `j - 1`

. The order in which it traverses the elements doesn’t matter, but it must cover each element in the range and ignore all elements outside the range.

Answer A incorrectly excludes the element at position `0`

.

Answer B correctly visits each element in the range and no other elements.

Answer C incorrectly excludes the element at position `0`

and incorrectly continues until the end of the array, rather than stopping at `j - 1`

. Although stopping at `j`

would also be acceptable, proceeding farther means that the loop will visit elements from the already sorted part of the array while seeking the maximum.

Answer D has a condition that would prevent the loop from running (`k > arr.length`

).

Answer E correctly includes the element at position `0`

, but also incorrectly continues into the already sorted part. Answer E also exceeds the bounds of the array by including `arr.length`

.

See Selection sort for the AP CS A Exam for a demonstration of the algorithm and other resources.

## Question 18

Let `c = x && y`

. The statement is equivalent to `c || !c`

which always evaluates to `true`

.

## Question 19

This question asks how to generate a random value in a specific range. See Generate random numbers with Math.random() for the appropriate technique. The application of the technique to this problem is below.

`d`

is the value resulting from a call to `Math.random()`

. `r`

is the variable to be set to a value in a specific range. We simplify this as shown below.

```
double r = Math.random();
// have: 0.0 <= r < 1.0
// want: 0.5 <= r < 5.5
double r = Math.random() * 5;
// have: 0.0 <= r < 5.0
// want: 0.5 <= r < 5.5
double r = Math.random() * 5 + 0.5;
// have: 0.5 <= r < 5.5
// want: 0.5 <= r < 5.5
```

This corresponds to answer choice (D).

## Question 20

Case I explicitly checks each part of the specified conditions and returns the correct value in each case.

Case II uses the same correct technique, but includes the extra variable `pass`

. `pass`

is initialized to `false`

then changed to `true`

if and only if one of the desired conditions is met. Case II works correctly.

Case III is a more efficient variant of the same combination of checks that avoids the `if`

statements and just returns the result of a single correct boolean condition. Case III works correctly.

## Question 21 (GridWorld Case Study)

The Quick Reference contains documentation for each `Location`

class method called. `loc2.getAdjacentLocation(Location.EAST)`

returns a `Location`

object representing (3, 3). The first condition evaluates to `true`

and `"aaa"`

is printed.

`loc1`

and `loc2`

have the same row value. The second condition is also `true`

and `"XXX"`

is printed.

`loc1.getDirectionToward(loc2)`

returns `270`

(`Location.WEST`

). The third condition is `false`

so nothing else is printed.

## Question 22 (GridWorld Case Study)

Case I correctly calculates the desired direction by getting the direction the bug is facing, adding `Location.RIGHT`

for the 90 degree right turn, then modding the result by `Location.FULL_CIRCLE`

(360) to correctly handle values that exceed 360. Case I then runs `super.turn()`

until the bug’s direction matches the desired direction. `super.turn()`

turns 45 degrees to the right, so running it repeatedly will eventually result in the bug facing in the desired direction. Case I works as intended.

Case II takes a much simpler approach and runs `super.turn()`

twice, which correctly accomplishes a 90 degree right turn.

Case III explicitly sets the direction to the bug’s original direction plus `Location.RIGHT`

. The `setDirection`

method handles values `>= 360`

so Case III also works correctly.

## Question 23 (GridWorld Case Study)

Both `Bug`

and `Critter`

extend `Actor`

which has method `getDirection`

. Lines 1, 2, and 3 are syntactically correct (do not cause a compile time error).

`Rock`

does not contain a `getMoveLocations`

method, so Line 4 is syntactically incorrect (causes a compile time error).

`Critter`

contains a `getMoveLocations`

method with the appropriate signature, so Line 5 is syntactically correct.

## Question 24 (GridWorld Case Study)

The `act`

method of `TestBug`

uses the `canMove`

and `move`

methods from its superclass `Bug`

. `canMove`

from `Bug`

checks if the location in front of the bug is empty or contains a flower while `move`

moves to the location in front of the bug.

When `act`

is run on `t`

, the `TestBug`

does the following:

- Checks its forward location (2, 2) and finds it empty
- Moves to location (2, 2)
- Checks the next forward location (1, 2) and finds it empty
- Moves to location (1, 2)

The code in the `else`

statement is never run. The bug just moves forward two locations and does not change its direction.

## Question 25 (GridWorld Case Study)

Case I: `DancingCritter.getActors`

returns a list of neighboring `DancingCritter`

objects rather than the list of all neighbors returned by `Critter.getActors`

. When `DancingCritter.processActors`

calls `super.processActors`

, the superclass method does not receive the neighbors it is supposed to remove.

Case II: `DancingCritter.processActors`

fails to call the superclass method to remove actors like a `Critter`

.

Case III: `makeMove`

is an acceptable place to turn. `DancingCritter.makeMove`

adheres to the postconditions of `makeMove`

, which permit turning.

## Question 26

This problem is most easily solved by tracing the loop for each value of `k`

. It can also be solved by recognizing the pattern; however, correctly identifying the number of times the loop runs is critical. A trace of the loop for each value of `k`

is below.

```
0: 0 is printed
2: 2 is printed
3: 0 is printed
5: 2 is printed
6: 0 is printed
8: 2 is printed
9: 0 is printed
```

`k`

becomes 11 and the loop terminates. All values are printed on the same line as: `0 2 0 2 0 2 0`

## Question 27

The given method should assume that all numbers are even until it is determined that at least one is not. `isEven`

should be initialized to `true`

and set to `false`

as soon as a number that is not even is detected. This is exactly what Answer C does.

Answer A initializes `isEven`

to `false`

and sets it to `true`

as soon as a single even number is found. This detects whether any number in `arr`

is even, not whether all numbers are even.

Answers B, D and E all contain the same error. The `else`

statement in each answer’s `/* loop body */`

means that the final value of `isEven`

is based only on the last value checked from `arr`

. The initial value assigned to `isEven`

is irrelevant as is the condition checked in each answer’s `if`

statement.

## Question 28

In the last line, `!result `

is equivalent to `!(x < y)`

which is equivalent to `(x >= y)`

.

The last line is equivalent to `( (x >= y) && (x >= y) )`

which will evaluate to `true`

if and only if `x >= y`

.

## Question 29

When `n`

is `4`

, the outer loop runs 4 times. For each run of the outer loop, the inner loop runs `outer + 1`

times. Each time the inner loop runs, it prints `outer`

. A trace of the output from the inner loop for each value of `outer`

is below.

```
0: 0
1: 1 1
2: 2 2 2
3: 3 3 3 3
```

All output is on the same line, so the output is `0 1 1 2 2 2 3 3 3 3`

## Question 30

Answers A and B compile because `Base`

has the required constructors. The reference and object types are identical.

Answer C compiles because `Sub`

(the object type) is a subclass of `Base`

(the reference type). Referring to a subclass object with a superclass reference is acceptable.

Answer D compiles because `Sub`

has the required constructor. The reference and object types are identical.

Answer E does not compile because `Sub`

does not have a constructor with a parameter (so `new Sub(5)`

is not syntactically valid). A subclass dooes not inherit constructors from its superclass.

## Question 31

If `a`

is not less than `b`

and `a`

is not greater than `b`

, `a`

must be equal to `b`

. The expression is equivalent to `a == b`

.

## Question 32

This problem is most easily solved by tracing the loop. A step by step trace is shown below.

```
Before 1st run
a: 24
b: 30
1st run
r: 24
a: 30
b: 24
2nd run
r: 6
a: 24
b: 6
3rd run
r: 0
a: 6
b: 0
```

The loop terminates after the 3rd iteration because `b != 0`

is `false`

. After the loop, `r`

does not exist (its scope is the loop), The value of `a`

is `6`

and the value of `b`

is `0`

. The `println`

statement prints `a`

which is `6`

.

## Question 33

The outer loop runs `lim`

times. The inner loop runs `lim - outer + 1`

times for each run of the outer loop. The value of `lim`

is `10`

. For each value of `outer`

, `s`

is incremented as shown below.

```
1: s += 10
2: s += 9
3: s += 8
...
10: s += 1
```

The value of `s`

is `10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1`

which is `55`

.

## Question 34

The loop must continue until `pos`

exceeds the bounds of `arr`

or until `val`

is found. To avoid an exception when checking `arr[pos]`

, the bounds check must be performed first.

Answer A correctly stops the loop when either condition described above is met. It also prevents an exception by checking that `pos`

is valid before checking `arr[pos]`

.

Answer B fails to ensure that `pos`

is valid before checking `arr[pos]`

, so it will crash if `val`

is not found.

Answer C incorrectly allows the loop to continue if either condition is `true`

rather than requiring that both be tru`e.

Answer D incorrectly continues the loop only if `val`

has been found, rather than when `val`

has not been found. It will also crash if it gets to the end of `arr`

(if every value is `val`

).

Answer E will always continue until it exceeds the bounds of `arr`

and crashes.

## Question 35

Case I visits the numbers 1, 4, 7, 10, 13, 16, 19 and prints those such that `k % 3 == 1`

. This condition is `true`

for each number visited, so the loop produces the desired output.

Case II visits each number `1 <= k < 20`

and prints those such that `k % 3 == 1`

. This condition is `true`

for each number in the desired output and no others, so the loop produces the desired output.

Case III visits the numbers 1, 4, 7, 10, 13, 16, 19 and prints each number. This produces the desired output.

## Question 36

All arguments in Java are passed by value. This means that the value of each parameter is set to a copy of the value of the corresponding argument. An object reference stores the memory address of an object, not the object itself. We often say the variable points to the object. Primitive type variables store their values directly.

All arrays in Java are objects, regardless of the type of the values inside the array. In `start`

, the value of `nums`

is the memory address of the array containing `[1, 2, 3, 4, 5]`

.

The value of `value`

is `6`

.

The call `changeIt(nums, value)`

passes the memory address of the array and `6`

. Within `changeIt`

, `list`

points to the same array to which `nums`

points. `num`

stores `6`

.

On the first line of `changeIt`

, a new array containing `[0, 0, 0, 0, 0]`

is created. The memory address of the new array is stored in `list`

. The change to the actual value of `list`

has no affect on the value of `nums`

, which still points to the original array containing `[1, 2, 3, 4, 5]`

.

In `changeIt`

, the value of `num`

is set to `0`

. This change has no effect on the value of `value`

, which is still `6`

.

The loop in `changeIt`

sets each value in the array to which `list`

points to `0`

, which has no effect outside the method.

When `changeIt`

ends, `list`

and `num`

go away. `nums`

and `value`

contain their original values. The array to which `nums`

points also contains its original values.

See Primitive types vs references exercises with method calls for step by step memory diagrams of passing parameters to methods.

See Arrays as objects exercises for detailed demonstrations of passing arrays (of both primitive type and object type) to methods.

## Question 37

The job of a constructor is to set the initial values of a an object’s instance variables. Class `NumSequence`

has one instance variable, `seq`

.

Case I incorrectly declares a local variable `seq`

and fills it with random values. The instance variable `seq`

remains `null`

.

Case II correctly initializes the instance variable and fills it with random values.

Case III declares a local variable `temp`

and initializes it to the memory address of an empty `ArrayList`

. Case III fills the `ArrayList`

to which `temp`

points with random values. Case III sets the instance variable `seq`

to the memory address of the `ArrayList`

to which `temp`

points. This works as intended.

## Question 38

Calculations with `double`

values are subject to roundoff error. Calculations with `int`

values are subject to overflow; however, `a`

and `b`

are not of type `int`

. None of the other answers would explain the discrepancy.

## Question 39

The method can be traced using recursive method tracing.

See a step by step trace of #39.

## Question 40

The method can be traced using recursive method tracing.

See a step by step trace of #40.