3 Take a Diagnostic Exam

5 Steps to a 5: AP Computer Science A 2024 - Klipp D.B., Johnson D.R., Paymer C.A. 2023

3 Take a Diagnostic Exam
STEP 2 Determine Your Test Readiness

IN THIS CHAPTER

Summary: This step contains a diagnostic exam that is exactly one-half the length of the actual AP Computer Science A Exam. However, in all other ways, it closely matches what you can expect to find on the actual test. Use this test to familiarize yourself with the AP Computer Science A Exam and to assess your strengths and weaknesses as you begin your review for the test.

Image

Key Ideas

Image Familiarize yourself with the types of questions and the level of difficulty of the actual AP Computer Science A Exam early in your test preparation process.

Image Use the diagnostic exam to identify the content areas on which you need to focus your test preparation efforts.

Using the Diagnostic Exam

The purpose of the diagnostic exam is to give you a feel for what the actual AP Computer Science A Exam will be like and to identify content areas that you most need to review.

When to Take the Diagnostic Exam

Since one purpose of the diagnostic exam is to give you a preview of what to expect on the AP Computer Science A Exam, you should take the exam earlier rather than later. However, if you are attempting the diagnostic exam without having studied Java yet, you may feel overwhelmed and confused. If you are starting this book in September, you may want to read a sampling of questions from the diagnostic exam, but then save the test until later when you know some Java. Taking the diagnostic exam when you begin to review will help you identify what content you already know and what content you need to revisit; then you can alter your test prep plan accordingly.

Take the diagnostic exam in this step when you begin your review, but save both of the full-length practice exams at the end of this book until after you have covered all of the material and are ready to test your abilities.

How to Administer the Exam

When you take the diagnostic exam, try to reproduce the actual testing environment as closely as possible. Find a quiet place where you will not be interrupted. Do not listen to music or watch a movie while taking the exam! You will not be able to do this on the real exam. Set a timer and stop working when the 90 minutes are up for each section. Note how far you have gotten so you can learn to pace yourself, but take some extra time to complete all the questions so you can find your areas of weakness. Use the answer sheet provided and fill in the correct ovals with a #2 pencil. Although this is a computer science exam, the AP Computer Science A exam is a paper-and-pencil test.

Part I of the exam contains Multiple-choice questions. For this diagnostic exam, give yourself 90 minutes to complete the 40 Multiple-choice questions. Note that there is no penalty for guessing on the exam, so if you’re not sure of an answer, eliminate obviously wrong answer choices and guess. You’ll find more helpful strategies to use in answering the Multiple-choice questions in Step 3.

Part II of the exam consists of Free-response questions. On this diagnostic exam, give yourself 90 minutes to complete the four Free-response questions. Strategies you can use to approach the Free-response question efficiently and effectively can be found in Step 3. Read those strategies after you’ve tried the diagnostic exam and become familiar with the types of questions on the exam.

After Taking the Diagnostic Exam

Following the exam, you’ll find not only the answers to the test questions, but also complete explanations for each answer. Do not just read the explanations for the questions you missed; you also need to understand the explanations for the questions you got right but weren’t sure of. In fact, it’s a good idea to work through the explanations for all the questions. Working through the step-by-step explanations is one of the most effective review tools in this book.

If you missed a lot of questions on the diagnostic exam or are just starting out learning how to program in Java, do not stress out! Step 4 of this book explains all of the concepts that will appear on the AP Computer Science A Exam. Read Units 010 in Step 4, do the practice questions for each unit, and read the explanations so you understand what the correct answer is and why it is correct. Then you’ll be well prepared for the AP Computer Science A Exam.

On the other hand, if you did well on some of the questions on the diagnostic exam and understand the explanations for these questions, you may be able to skip some of the units in Step 4. Look at the summaries and key ideas that begin each of the units in Step 4. If you’re reasonably sure you understand a concept already, you may want to skip to that unit’s review questions or the “Rapid Review” and then move on to the next unit. A good test prep plan focuses on the areas you most need to review.

Now let’s get started.

Diagnostic Exam

Multiple-Choice Questions

ANSWER SHEET

Image

AP Computer Science A Diagnostic Exam

Part I

Multiple Choice

Time: 90 minutes

Number of questions: 40

Percent of total score: 50

Directions: Choose the best answer for each problem. Use available space for scratch work and hand tracing. Some problems take longer than others. Consider how much time you have left before spending too much time on any one problem.

Notes:

• You may assume that all import statements have been included where they are needed.

• You may assume that the parameters in method calls are not null and the methods are called when their preconditions are met.

• You may assume that declarations of variables and methods appear within the context of an enclosing class.

• You may refer to the Java Quick Reference sheet as needed.

1. Consider the following method.

Image

What value is returned by the call someMethod(13)?

(A) 17

(B) 25

(C) 28

(D) 31

(E) Nothing is returned. There is a compile-time error.

2. Consider the following code segment.

Image

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

(A) -11

(B) 4

(C) 11

(D) 13

(E) 15

3. Assume list is an ArrayList that has been correctly constructed and populated with the following items.

Image

Consider the following method.

Image

What value is returned by the call calculate(list)?

(A) 10

(B) 11

(C) 13

(D) 35

(E) 45

4. Consider the following class declarations.

Image

Which of the following declarations compiles without error?

I. Planet mars = new Planet();

II. Planet pluto = new DwarfPlanet("Pluto");

III. Planet ceres = new DwarfPlanet();

(A) I only

(B) II only

(C) I and II only

(D) I and III only

(E) I, II, and III

5. Consider the following code segment.

Image

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

(A) [Zombie, Werewolf, Mummy, Witch]

(B) [Zombie, Werewolf, Ghost, Witch]

(C) [Zombie, Werewolf, Mummy, Ghost]

(D) [Zombie, Vampire, Werewolf, Mummy, Ghost]

(E) [Zombie, Vampire, Werewolf, Mummy, Witch]

6. Suppose that grid has been initialized as n-by-n 2D array of integers. Which code segment will add all values that are along the two diagonals?

Image

7. Consider the following partial class declaration.

Image

Assume that the following declaration has been made in the main method of another class.

Image

Which of the following statements compiles without error?

(A) int num = park.acres;

(B) String name = central.getName();

(C) boolean play = park.hasPlayground();

(D) int num = park.getAcres(acres);

(E) park.hasPlayground = true;

8. Consider the following code segment.

Image

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

(A) mmm

(B) nonono

(C) mnomno

(D) nomnono

(E) mnomnomno

9. Consider the following method.

Image

What value is returned by the call loopy(12)?

(A) 12

(B) 21

(C) 23

(D) 27

(E) 29

10. Consider the following class declarations.

Image

Consider the following code segment.

Image

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

(A) abA

(B) aba

(C) letterlettera

(D) letterletterletter

(E) Nothing is printed. There is a compile-time error.

11. Consider the following method.

Image

What is returned by the call lengthen("APCS")?

(A) "APCS"

(B) "APCSACAA"

(C) "APCSAPCS"

(D) Nothing is returned. Run-time error: StringIndexOutOfBoundsException

(E) Nothing is returned. The call will result in an infinite loop.

12. Consider the following code segment.

Image

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

Image

13. Assume that k, m, and n have been declared and correctly initialized with int values. Consider the following statement.

boolean b1 = (n >= 4) || ((m == 5 || k < 2) && (n > 12));

For which statement below does b2 = !b1 for all values of k, m, and n?

(A) boolean b2 = (n >= 4) && ((m == 5 && k < 2) || (n > 12));

(B) boolean b2 = (n < 4) || ((m != 5 || k >= 2) && (n <= 12));

(C) boolean b2 = (n < 4) && (m != 5) && (k >= 2) || (n <= 12);

(D) boolean b2 = (m == 5 || k < 2) && (n > 12);

(E) boolean b2 = (n < 4);

14. Consider the following code segment.

Image

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

(A) Nothing is printed. Runtime error: ArrayIndexOutOfBounds

(B) 18

(C) 181620

(D) 68

(E) 1820

15. Consider the following method.

Image

Assume that the string codeword has been declared and initialized as follows.

String codeword = "advanced placement";

What value is returned by the call mystery(codeword, 9)?

(A) 5

(B) 6

(C) 7

(D) Nothing is returned. Infinite recursion causes a stack overflow error.

(E) Nothing is returned. Run-time error: StringIndexOutOfBoundsException

16. Consider the following method.

Image

Consider the following code segment.

Image

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

Image

17. Consider the following code segment.

Image

Consider these additional code segments.

I. Image

II. Image

III. Image

Which of the code segments produce the same output as the original code segment?

(A) I only

(B) II only

(C) III only

(D) II and III only

(E) I, II, and III

18. Consider the following method.

Image

The method above could be best described as an implementation of which of the following?

(A) Insertion Sort

(B) Binary Search

(C) Selection Sort

(D) Merge Sort

(E) Sequential Sort

19. Consider the following statement.

int number = (int)(Math.random() * 21 + 13);

After executing the statement, what are the possible values for the variable number?

(A) All integers from 13 to 21 (inclusive).

(B) All real numbers from 13 to 34 (not including 34).

(C) All integers from 13 to 34 (inclusive).

(D) All integers from 13 to 33 (inclusive).

(E) All real numbers from 0 to 21 (not including 21).

20. Consider the following class declaration.

Image

Assume ArrayList cities has been properly instantiated and populated with City objects.

Consider the following code segment.

Image

Which of the following should replace /* missing code */ so that, after execution is complete, maxPop will contain the largest population that exists in the ArrayList?

(A) Image

(B) Image

(C) Image

(D) Image

(E) maxPop should have been set to Integer.MAX_VALUE. This cannot work as written.

21. Consider the following method.

Image

Which statement best describes the value that is returned by mystery?

(A) Ten to the nth power is returned.

(B) The number of digits in n is returned.

(C) The number of times 10 is a factor of n is returned.

(D) The number whose digits are the reverse of n is returned.

(E) The sum of the digits in n is returned.

22. Consider the following code segment.

Image

What output is produced by executing this code?

(A) x = 2, y = 4

(B) x = 6, y = 6

(C) x = 6, y = 10

(D) x = 6, y = 12

(E) x = 24, y = 42

Questions 23 and 24 refer to the following class hierarchy.

Image

23. What is printed as a result of executing the following code? (Assume that all the classes have parameterless constructors.)

Image

(A) Nothing; the code does not compile.

(B) alpha eeny

(C) alpha eeny alpha eeny

(D) alpha eeny gamma eeny

(E) miny gamma eeny

24. What is printed as a result of executing the following code? (Assume that all the classes have parameterless constructors.)

Image

(A) Nothing; the code does not compile.

(B) alpha eeny alpha eeny

(C) delta eeny

(D) delta eeny alpha eeny

(E) delta eeny delta eeny alpha eeny

25. Assume that an ArrayList names holds the following values.

Image

What values does this ArrayList hold after executing the following code?

Image

(A) Debbie, Rob, Kelly, Sandy, Kim, J.P.

(B) Debbie, J.P., Andy, Tim, Alistair, Judy

(C) Debbie, Kelly, Kim, Andy, Alistair, Judy

(D) Rob, Sandy, J.P., Tim, Alistair, Judy

(E) Kim, J.P., Andy, Tim, Alistair, Judy

26. Consider the following method.

Image

What value is returned by a call to method solve?

(A) 0.0

(B) The kth root of n

(C) 1/n

(D) 1/(n-1)

(E) (1/2)n

27. Consider the following method.

Image

What is returned by evaluate?

(A) evaluate always returns false

(B) evaluate returns true when p and q are both true or both false

(C) evaluate returns true only when p and q are both true

(D) evaluate returns true only when p and q are both false

(E) evaluate returns true when either p or q is true and the other is false

28. Consider the following class declaration.

Image

Assume the following valid declarations have been made.

Image

Which of the following statements in a client program is valid?

Image

29. Suppose that glop is an ArrayList of DooHickeys. Consider the following code fragment that is meant to print out the ID numbers of all DooHickeys whose mass is greater than zero.

Image

Which of the following expressions will complete the code fragment correctly?

(A) Doohickeys.get(num).getMass() > 0

(B) getNum(glop).getMass() > 0

(C) glop[num].getMass() > 0

(D) glop.get(num).getMass() >0

(E) glop.get(glop.getMass(num)) > 0

30. Consider the following method, which is intended to count the number of times a value is doubled before it is at least as large as a target value.

Image

Of the following, which best describes the error in doubleUp?

(A) The static modifier cannot be used with a constant.

(B) A variable is used without being initialized.

(C) A double cannot be multiplied by an int.

(D) The counter is incremented in the wrong place.

(E) A variable is initialized in the wrong place.

Question 31 and 32 refer to the following method.

Image

31. Which of the following is the best precondition for method check?

(A) 0 <= n < arr.length

(B) n < arr.length

(C) n <= arr.length

(D) n >= 0

(E) No precondition is necessary.

32. Which of the following is the best postcondition for method check?

(A) returns true if there are no duplicates in the first n elements of arr; otherwise, returns false

(B) returns true if the (n-1)th element of arr is less than the nth element; otherwise, returns false

(C) returns true if the first n elements of arr are all the same value; otherwise, returns false

(D) returns true if the first n elements of arr are in strictly increasing order; otherwise, returns false

(E) returns true if there are an even number of times when an element is at least as large as its successor among the first n elements of arr; otherwise, returns false

33. Assuming that b is a boolean variable, what will be the result of executing the code?

b = (b != b)

(A) Sets b to false

(B) Sets b to true

(C) Changes the value of b to its opposite

(D) Leaves the value of b unchanged

(E) The code will not compile.

34. Consider the following class declaration.

Image

Assuming that x is a properly constructed SimpleInt, which of the following statements will compile in a program that uses SimpleInt?

Image

(A) I only

(B) II only

(C) I and II only

(D) I and III only

(E) I, II, and III

35. Which expression below is equivalent to the following? (Assume x and y are Strings.)

Image

36. A programmer has mistakenly placed a semicolon at the end of the while statement in the following code fragment. What will be the result of executing the code?

Image

(A) The code will behave in the same manner as if the semicolon were not included.

(B) The program will get caught in an infinite loop, appearing to do nothing.

(C) The program will get caught in an infinite loop, repeatedly printing the message, “in loop”.

(D) Depending on the code that precedes this loop within the program, either an infinite loop will result or the “in loop” message will be printed one time.

(E) The code will not compile because of the presence of the semicolon at the end of the while statement.

37. Consider the following incomplete method that is intended to determine if the corresponding elements of two parallel arrays are equal.

Image

Which of the following is a valid replacement for < missing code>?

(A) Image

(B) Image

(C) Image

(D) Image

(E) Image

For questions 38 and 39, consider the inheritance hierarchy shown below.

Image

38. Suppose that we wish to add the class Snake to this hierarchy. Which of the two implementation schemes below is more appropriate and why?

I. The class Snake should extend the class Animal

II. The class Snake should extend the class Cat

(A) Implementation I is a better choice because it is the case that Snake IS-A Animal, but it is not the case that Snake IS-A Cat.

(B) Implementation I is a better choice because the code will be shorter and easier to understand.

(C) Implementation II is a better choice because the Snake class can inherit most of its operations from the Cat class.

(D) Implementation II is a better choice because it leads to a deeper inheritance hierarchy.

(E) The two implementations are approximately equivalent.

39. Which of the following is NOT true about the data and methods in the various classes?

(A) A Dog object may use public instance variables declared in the Animal class.

(B) An Animal object may use public instance variables associated with a separate Dog object.

(C) A Cat object may use private instance variables declared in the Animal class.

(D) A Cat object may invoke public methods declared in the Animal class.

(E) A Cat object may use private instance variables associated with a separate Dog object whenever appropriate access methods are provided.

40. Consider the following recursive method.

Image

What value will be printed by the call mystery(5)?

(A) 1

(B) 3

(C) 4

(D) 7

(E) 11

STOP. End of Part I.

AP Computer Science A Diagnostic Exam

Part II

Free Response

Time: 90 minutes

Number of questions: 4

Percent of total score: 50%

Directions: Write all of your code in Java. Show all your work.

Notes:

• You may assume all import statements have been included where they are needed.

• You may assume that all preconditions are met when making calls to methods.

• You may assume that all parameters within method calls are not null.

• Be aware that you should, when possible, use methods that are defined in the classes provided as opposed to duplicating them by writing your own code. Doing so you will not receive full credit.

• You may use the Java Quick Reference sheet as needed.

1. The StringRotation class contains methods used to determine if a string is a rotation of another string. The declaration of the StringRotation class is shown below. You will write two methods of this class.

Image

(a) Write the static method findNumberOfRotations, which returns the number of rotations necessary for rotation and base to have the same value. A String is considered a rotation of another String if the order of the letters remains the same, but the positions of the letters are shifted, causing the letters at the end of the String to shift to the beginning of the String. If no rotations are possible for the values of rotation and base to be the same, then -1 is returned.

The chart contains a sample code execution and the corresponding result.

Image

(b) Write the static method isReverseRotation, which returns true if rotation is a reverse rotation of base and false otherwise. A String is considered a reverse rotation of another String if the reverse of the string is a rotation of the other. You may call on findNumberOfRotations and assume it works as intended, regardless of your implementation.

The chart contains a sample code execution and the corresponding result.

Image

2. The class FurnitureItem represents a furniture item sold at a local furniture store.

Image

The furniture store offers a special summer promotion that includes a discount if two items are purchased from the same set. You will write a class SummerSpecial to represent the result of purchasing two FurnitureItem objects, based on the following rules and the examples in the chart that follows.

• The set to which a FurnitureItem belongs is identified by the last five characters of the item’s product ID. For example, a chair with product ID C-123456-APCSA and a table with product ID T-987-APCSA both belong to the APCSA furniture set. Note that product IDs from different items may differ in length.

• If two items belong to the same set, the total price is calculated by deducting 25% from the price of the more expensive item and then adding the price of the less expensive item.

• If two items do not belong to the same set, the total price is calculated by deducting 10% from the price of the least expensive item and then adding the price of the more expensive item.

Assume FurnitureItem objects item1, item2, and item3 have been created as follows.

• FurnitureItem item1 is a chair with product ID C-123456-APCSA and a price of $250.

• FurnitureItem item2 is a table with product ID T-9876-APCSA and a price of $500.

• FurnitureItem item3 is a chair with product ID C-2468-APCSP and a price of $125.

The chart contains a sample code execution sequence and the corresponding results.

Image

Write the complete SummerSpecial class. Your implementation must meet all specifications and conform to the examples shown in the preceding chart. Note that you must call isSet() from within the getPrice() method to earn full credit.

3. The class Route represents a route that can be stored in a GPSRouter object.

Image

The class GPSRouter represents a collection of Route objects. Assume that the collection routes has been initialized.

Image

You will write two methods from the class GPSRouter as follows:

• The method maxMileage will find the Route object in the GPSRouter object with the largest number of miles and return it. If the GPSRouter object has no routes, then the method will return null.

• The method addMiles will add a route to the GPSRouter object with the given name based on the following requirements:

• Routes in a GPSRouter object are identified by name. All routes in a GPSRouter object have unique names.

• If the route is already represented in the GPSRouter object (has the same name as the given name routeName), then increase the mileage in the corresponding route by the given amount mileage.

• If the route is not already represented in the GPSRouter object (the given name routeName does not match any name in the collection), then add a new Route to the collection with the given name routeName and mileage mileage.

Assume a GPSRouter object gps has been created and the following routes (already created) have been added into it.

• Route route1 is a Route with name “Kalamazoo” and a mileage of 5200.

• Route route2 is a Route with name “Tampa” and a mileage of 7000.

• Route route3 is a Route with name “Dayton” and a mileage of 1000.

The chart contains a sample code execution sequence and the corresponding results.

Image

a) Write the implementation for the maxMileage method of the GPSRouter class, which will return the Route object with the largest number of miles. If there are no routes in the GPSRouter object, return null.

Image

b) Write the implementation of the addMiles method of the GPSRouter class, which updates the milage of the given Route if it exists in the collection and adds the given Route to the collection if it does not.

Image

4. Coin Collector

The High School Coin Collection Club needs new software to help organize its coin collections. Each coin in the collection is represented by an object of the Coin class. The Coin class maintains three pieces of information for each coin: its country of origin, the year it was minted, and the type of coin it is. Because coin denominations vary from country to country, the club has decided to assign a coin type of 1 to the coin of lowest denomination, 2 to the next lowest, and so on. For American coins, coinType is assigned like this:

Image

Image

The Coin Club currently keeps track of its coins by maintaining an ArrayList of Coin objects for each country. The coins in the ArrayList are in order by year, oldest to newest. If two or more coins were minted in the same year, those coins appear in a random order with respect to the other coins from the same year.

The Coin Club has acquired some new collection boxes of various sizes to store their coins. The boxes are rectangular and contain many small compartments in a grid of rows and columns. The club will store coins from different countries in different boxes.

The CoinCollectionTools class below assists the Coin Club in organizing and maintaining their collection.

Image

(a) The CoinCollectionTools class constructor initializes the instance variable coinBox as a two-dimensional array of Coin objects with dimensions specified by the parameters. It then instantiates each of the Coin objects in the array as a default Coin object with country equal to the country name passed as a parameter, year equal to 0, and coinType equal to 0.

Image

(b) The Coin Club intends to fill the collection boxes from their list of coins, starting in the upper-left corner and moving down the columns in order until all Coin objects have been placed in a compartment.

The fillCoinBox method takes as a parameter an ArrayList of Coin objects in order by year minted and returns a chart showing their position in the box, filled in column-major order.

You may assume that coinBox is initialized as intended, regardless of what you wrote in part (a).

Complete the method fillCoinBox.

Image

(c) Sometimes the Coin Club would prefer to see a list of its coins organized by coin type.

The fillCoinTypeList method uses the values in coinBox to create and return an ArrayList of Coin objects filled first with all the Coin objects of type 1, then type 2, and so on through type 6. You may assume that no country has more than 6 coin types. Note that the number of coins from any specific type may be 0.

Since the original coinBox was filled in column-major order, Coin objects should be retrieved from the coinBox in column-major order. This will maintain ordering by year within each coin type.

Remember that the CoinCollectionTools class constructor filled the coinBox with default Coin objects with a coinType of 0, so no entry in the coinBox is null.

You may assume that coinBox is initialized and filled as intended, regardless of what you wrote in parts (a) and (b).

Complete the method fillCoinTypeList.

Image

STOP. End of Part II.

Diagnostic Exam Answers and Explanations

Part I (Multiple-Choice) Answers and Explanations

Bullets mark each step in the process of arriving at the correct solution.

1. The answer is B.

• When we first enter the loop, val = 13 and i = 2. The if condition is looking for even numbers. Since val + i is odd, we skip the if clause. Increment i to 3. i < 7 so we continue.

• val = 13, i = 3. This time val + i is even, so add 3 to val. val = 16, increment i to 4, i < 7 so we continue.

• val = 16, i = 4. val + i is even, add 3 to val. val = 19, increment i to 5, i < 7, continue.

• val = 19, i = 5. val + i is even, add 3 to val. val = 22, increment i to 6, i < 7, continue.

• val = 22, i = 6. val + i is even, add 3 to val. val = 25, increment i to 7. This time, when we check the loop condition, i is too big, so we exit the loop.

• val = 25 and that is what is returned.

2. The answer is E.

• The first if condition evaluates to (2 < 5 && 13 < 5), which is false, so we skip to the else clause.

• The else clause has its own if statement. The condition evaluates to (2 == 2 && 13 < 2), which is false, so we skip to the else clause.

• result = 2 + 13 = 15, which is what is printed.

3. The answer is D.

• The for-each loop can be read like this: for each integer in numbers, which I am going to call n.

• The if clause is executed only when the element is > 8, so the loop adds all the elements greater than 8 to the sum variable.

• The elements greater than 8 are 13, 12, and 10, so sum = 35, and that is what the method returns.

4. The answer is C.

• Option I is correct. The reference variable type Planet matches the Planet object being instantiated, and the Planet class contains a no-argument constructor.

• Option II is correct. The reference variable type Planet is a superclass of the DwarfPlanet object being instantiated, and the DwarfPlanet class contains a constructor that takes one String parameter.

• Option III is not correct. Although the reference variable type Planet is a superclass of the DwarfPlanet object being instantiated, the DwarfPlanet class does not contain a no-argument constructor. Unlike a method, the constructor of the parent class is not inherited.

5. The answer is A.

• Let’s picture the contents of our ArrayList in a table. After the 3 adds, we have:

Image

Setting 0 to Zombie gives us:

Image

Adding Mummy at position 2 pushes Ghost over one position:

Image

Witch gets added at the end:

Image

After the remove at index 3, Ghost goes away and Witch shifts over one:

Image

6. The correct answer is E.

• Options A and B are incorrect. The inner column loop is not necessary and includes more values than along the diagonal to be included in the sum.

• Option C is incorrect. If the grid has odd dimensions, the center value will be counted twice.

• Option D is incorrect. If the grid has even dimensions, one value in the main diagonal will be subtracted out of the sum at the end.

• Option E works correctly. If the grid has odd dimensions, the center value will only be counted once.

7. The answer is C.

• Option A will not compile, because acres is a private instance variable.

• Option B will not compile, because the name of the object is park, not central.

• Option C is correct. The method is called properly and it returns a boolean.

• Option D will not compile, because getAcres does not take a parameter.

• Option E will not compile, because hasPlayground is not a public boolean variable.

8. The answer is B.

• The for loop goes through the entire string, looking at each character individually. If the character is an m, the substrings add the section of the string before the m to the section of the string after the m, leaving out the m.

• The result is that all the m’s are removed from the string, and the rest of the string is untouched.

9. The answer is D.

• This is a recursive method. Let’s trace the calls. The parts in italics were filled in on the way back up. That is, the calls in the plain type were written top to bottom until the base case returned a value. Then the answers were filled in bottom to top.

Image

10. The answer is B.

• The compiler looks at the left side of the equals sign and checks to be sure that whatever methods are called are available to variables of that type. Since Letter and ALetter both contain toString methods, the compiler is fine with the code. Option E is incorrect.

• The run-time environment looks at the right side of the equals sign and calls the version of the method that is appropriate for that type.

• System.out.print(x) results in an implicit call to the ALetter toString method, and prints "a".

• System.out.print(y) results in an implicit call to the BLetter toString method and prints "b".

• System.out.print(z) tries to make an implicit call to a CapALetter toString method, but there isn’t one, so it moves up the hierarchy and calls the toString method of the ALetter class and prints "a".

11. The correct answer is B.

• On entry, word = "APCS" and index = 0.

word = word + its substring from 0 to 1, or "A". word = "APCSA".

• Add 2 to index, index = 2. word.length() is 5, 2 < 5 so continue.

word = word + its substring from 2 to 3, or "C". word = "APCSAC".

• Add 2 to index, index = 4. word.length() is 6, 4 < 6, so continue.

word = word + its substring from 4 to 5, or "A". word = "APCSACA".

• Add 2 to index, index = 6. word.length() is 7, 6 < 7, so continue.

word = word + its substring from 6 to 7, or "A". word = "APCSACAA".

• Add 2 to index, index = 8. wordlength() is 8, 8 is not < 8 so the loop exits.

• Notice that since word is altered in the loop, word.length() is different each time we evaluate it at the top of the loop. You can’t just replace it with 4, the length of word at the beginning of the method. You must re-evaluate it each time through the loop.

12. The answer is C.

• Each time through the loop:

• We are considering element n.

• We calculate array[n] − array[n − 1] and compare it to array[n] − array[n + 1]. In other words, subtract the element before from the nth element, then subtract the element after from the nth element. If the before subtraction <= the after subtraction, print n.

• Let’s make a table. As a reminder, here is our array:

{-3, 0, 2, 4, 5, 9, 13, 1, 5}

Image

• Printing array[n] in the YES cases gives us 13 1. Remember that we are printing the element, not the index.

13. The answer is C.

• We want to negate our expression, so we are trying to solve this (note the added ! at the beginning).

!((n >= 4) || ((m == 5 || k < 2) && (n > 12)))

• DeMorgan’s theorem tells us that we can distribute the !, but we must change AND to OR and OR to AND when we do that. Let’s take it step by step.

• Distribute the ! to the 2 expressions around the || (which will change to &&).

!(n >= 4) && !((m == 5 || k < 2) && (n > 12)))

• !(n >=4) is the same as (n < 4).

(n < 4) && !((m == 5 || k < 2) && (n > 12)))

• Now let’s distribute the ! to the expression around the second && (which becomes ||).

(n < 4) && !(m == 5 || k < 2) || !(n > 12)

• Fix the !(n > 12) because that’s easy.

(n < 4) && !(m == 5 || k < 2) || (n <= 12)

• One to go! Distribute the ! around the || in parentheses (which becomes &&).

(n < 4) && !(m == 5) && !(k < 2) || (n <= 12)

• Simplify those last two simple expressions.

(n < 4) && (m != 5) && (k >= 2) || (n <= 12)

• A good way to double-check your solution is to assign values to m, n, and k and plug them in. If you do not think you can simplify the expression correctly, assigning values and plugging them in is another way to find the answer, though you may need to check several sets of values to be sure you’ve found the expression that works every time.

14. The answer is E.

• Consider Option A. Can an index be out of bounds? The largest values m and n will reach are 4 and 6, respectively. 4 + 6 = 10, and ray[10] is the 11th element in the array (because we start counting at 0). The array has a length of 11, so we will not index out of bounds.

• Look at the first for loop. The array is being filled with elements that are equal to twice their indices, so the contents of the array look like { 0, 2, 4, 6, 8, … }.

• Look at the nested for loop. The outer loop will start at m = 0 and continue through m = 4. For each value of m, n will loop through 0, 2, 4, 6, because n is being incremented by 2. (It’s easy to assume all loops use n++. Look!)

• We are looking for m + n > 8. Since the largest value for n is 6, that will not happen when m is 0, 1, or 2.

• The first time m + n is greater than 8 is when m = 3 and n = 6.

ray[3 + 6] = ray[9] = 2 * 9 = 18. Print 18.

• The next time m + n is greater than 8 is when m = 4 and n = 6.

ray[4 + 6] = ray[10] = 2 * 10 = 20. Print 20.

• Notice that we aren’t printing any spaces, so the 1820 are printed right next to each other.

15. The answer is E.

• This is a recursive method. Let’s trace the calls.

Image

• By this point we should have noticed that we are getting farther and farther from the base case. What will happen when we run out of characters? Let’s keep going and see.

Image

• "nt".substring(2) is, somewhat surprisingly, a valid expression. You are allowed to begin a substring just past the end of a string. This call will return an empty string.

mystery ("nt", 17) = mystery("", 18)

• This time code.substring(2) fails: StringIndexOutOfBoundsException.

16. The answer is A.

• This problem requires you to understand that primitives are passed by value and objects are passed by reference.

• When a primitive argument (or actual parameter) is passed to a method, its value is copied into the formal parameter. Changing the formal parameter inside the method will have no effect on the value of the variable passed in; num and index will not be changed by the method.

• When an object is passed to a method, its reference is copied into the formal parameter. The actual and formal parameters become aliases of each other; that is, they both point to the same object. Therefore, when the object is changed inside the method, those changes will be seen outside of the method. Changes to array nums inside the method will be seen in array val outside of the method.

• num and index remain equal to 10 and 3, respectively, but val[3] has been changed to 10.

17. The answer is B.

• The original code segment is a nested loop. The outer loop has an index, which will take on the values 2, 4, 6. For each of those values, the inner loop has an index, which will take on the values 30, 20, 10. The code segment will print:

Image

We need to see which of I, II, III also produce that output.

• Option I is a for loop. On entry, num = 32, count = 0, i = 0.

• 32 is printed, num = 34, count % 3 = 0, so we execute the if clause and set count = 0 and num = 20.

• Next time through the loop, 20 is printed … oops, no good! Eliminate option I.

• Option II is a while loop. On entry, num = 32.

• 32 is printed, num = 22, if condition is false.

• Next time through the loop, 22 is printed, num = 12, if condition is false.

• 12 is printed, num = 2, if condition is true, num = 34.

• 34 is printed, num = 24, if condition is false.

• 24 is printed, num = 14, if condition is false.

• 14 is printed num = 4, if condition is true, num = 36.

• 36 is printed, num = 26, if condition is false.

• 26 is printed, num = 16, if condition is false.

• 16 is printed, num = 6, if condition is true, num = 38.

• Loop terminates — looks good! Option II is correct.

• Option III is a nested for loop.

• The first time through the loops, h = 0, k = 30.

• h + k = 30, so 30 is printed. That’s incorrect. Eliminate option III.

18. The answer is A.

• This is one way of implementing the Insertion Sort algorithm. The interesting thing about this implementation is the use of a compound condition in the for loop. This condition says “Continue until you reach the beginning of the array OR until the element we are looking at is bigger than the key.” When the for loop exits, the “key” is put into the open slot at position j. That’s an Insertion Sort algorithm.

• Looking at this problem a different way:

• It can’t be B. If this were a search algorithm, there would have to be a parameter to tell us what element we are looking for, and that isn’t the case.

• It can’t be D because Merge Sort is recursive and there’s no recursion in this code segment.

• It can’t be E, because we know Sequential Search but there isn’t a Sequential Sort.

• That just leaves Selection Sort. Selection Sort has nested for loops, but the loops have no conditional exit. They always go to the end of the array. And on exit, elements are swapped. There’s no swap code here.

19. The answer is D.

• The general form for generating a random number between high and low is

(int)(Math.random * (high - low + 1) + low

• high — low + 1 = 21, low = 13, so high = 33.

• The correct answer is integers between 13 and 33 inclusive.

20. The answer is D.

• Option A is incorrect. It uses array syntax rather than ArrayList syntax to retrieve the element.

• Option B is incorrect. It attempts to access the instance variable population directly, but population is private (as it should be).

• Option C is incorrect. First of all, the algorithm is wrong. It is only comparing the population in consecutive elements of the ArrayList, not in the ArrayList overall. In addition, it will end with an IndexOutOfBoundsException, because it uses (i + 1) as an index.

• Option D works correctly. It accesses the population using the getter method, and it compares the accessed population to the previous max.

• Option E is incorrect. If we began by setting maxPop = Integer.MAX_VALUE, then that is the value maxPop will have when the code segment completes.

21. The answer is D.

• Variable a holds the integer quotient of n divided by 10 and b the remainder of the division.

• To reverse n, variable c is multiplied by 10, and the new remainder is added.

• The process continues, multiplying by 10 to move the current value over one place value, until the integer quotient is 0.

22. The answer is C.

• In the third line of code x = x + y = 2 + 4 = 6.

• In the fourth line of code y = y + x = 4 + 6 = 10.

23. The answer is D.

• Beta extends Alpha. Beta does not have a method eeny so b.eeny invokes eeny from the superclass.

• The second invocation is made on a Gamma object, so that code generates the second portion of the output.

• Note that a is defined as a new Gamma, and a Gamma IS-A Alpha.

• Look first to the subclass, Gamma, to see if it has overridden method eeny before looking to the superclass, Alpha.

• It has an overridden method, so a.eeny invokes eeny from the Gamma class.

24. The answer is D.

• When methods are overloaded, the parameters determine which version of the method will be invoked.

• The second statement calls the eeny method from the Delta class (there is one parameter).

• The third statement calls the eeny method from the Alpha class (there are two parameters).

25. The answer is C.

• When the element in position 1 is removed, all remaining elements shift “down” one position.

• The element that was in position 2 fills in for the removed element and, therefore, is now in position 1.

• The loop counter moves to position 2, resulting in a skipped name.

• In fact, because the list shrinks with each iteration, every other name is skipped.

26. The answer is C.

• The code keeps a running product: (1/2)(2/3)(3/4) … [n/(n+1)].

• The result of this multiplication is 1/n.

27. The answer is B.

• If p and q are different, then the first part of the expression is always false.

• If p and q are different, then p || q is true, thus the negation will be false.

• So, the expression is false whenever p and q are different.

A truth table might also help.

Image

28. The answer is D.

• Option A is not correct for two reasons. row is a private instance variable and cannot be accessed outside the class. Strings must be compared using either the equal or compareTo method.

• Option B is not correct since the setSeatLocation method needs to be passed a SeatLocation parameter.

• Option C is not correct since the getSeatLocation method should not be passed any parameters.

• Option D is correct. The call to setPrice correctly takes a double parameter and the call to getPrice is called correctly without parameters.

• Option E is not correct. The for loop cannot traverse through the rows as shown.

29. The answer is D.

• Option A is incorrect since the get method must be called on the ArrayList glop, not on the class DooHickey.

• Option B is incorrect since there is no getNum method defined.

• Option C incorrectly uses array syntax for accessing the element.

• Option E uses an improper invocation of a parameterless method.

30. The answer is E.

• The count is reinitialized to 0 on each pass through the loop.

31. The answer is C.

• To avoid an exception, we must know that only valid subscripts are used to index the array.

• Each time through the loop, we access the (k+1)th cell, so we must be sure that k < arr.length-1.

• The loop condition guarantees the k < n-1, thus n can be no larger than arr.length.

32. The answer is E.

• Each time a value is found that is not less than its successor, the boolean variable theCheck is set to the opposite value.

• If this happens an even number of times, theCheck will be true; otherwise, it will be false.

33. The answer is A.

• The test for b not being equal to itself will be false in all cases.

34. The answer is A.

• Statement I correctly calls a method of the class.

• Statement II incorrectly attempts to access private data in the class.

• Statement III incorrectly attempts to use data from a void method.

35. The answer is E.

• Options A and B incorrectly use the .equals method with null.

• Option E correctly applies DeMorgan’s Law.

36. The answer is D.

• If j < n is true, the program will get caught in an infinite loop.

• If j >= n, the while loop condition is false and the loop will not be executed. The body of the loop will be treated as the next statement to be executed, and the “in loop” message will be printed one time.

37. The answer is E.

• Option A will return after the first elements are checked for equality.

• Option B will return true as soon as two parallel elements are found to be equal. It will not determine if all the parallel elements are equal.

• Option C will test each parallel elements for equality, but will only return the result of the test for the last two elements.

• Option D always returns true since same is never changed inside the loop.

• Option E returns true if the loop counter traverses the entire list; otherwise, there is an early exit from the loop and false is returned.

38. The answer is A.

• Inheritance should always reflect the IS-A relationship between classes.

• The claims of options B and C may or may not be true, but they would be less important than the IS-A relationship in any case.

• Option D implies that deeper inheritance hierarchies are somehow better than shallow ones, which is not necessarily true.

39. The answer is C.

• Options A and B are true, but classes should declare all instance variables private.

• Subclasses do not have direct access to private information in the superclass. An accessor method must be used.

• Public variables and methods are always available for other objects to use.

40. The answer is D.

• Let’s trace the code. The parts in italics were filled in on the way back up. That is, the calls in the plain type were written top to bottom until the base case returned a value. Then the answers were filled in bottom to top.

mystery(5) → mystery(4) + mystery(3) → 4 + 3 = 7

mystery(4) → mystery(3) + mystery(2) → 3 + 1 = 4

mystery(3) → 3

mystery(2) → mystery (1) + mystery(0) → 1 + 0 = 1

Part II (Free-Response) Solutions

Please keep in mind that there are multiple ways to write the solution to a Free-response question, but the general and refined statements of the problem should be pretty much the same for everyone. Look at the algorithms and coded solutions, and determine if yours accomplishes the same task.

General penalties (assessed only once per problem):

-1 using a local variable without first declaring it

-1 returning a value from a void method or constructor

-1 accessing an array or ArrayList incorrectly

-1 overwriting information passed as a parameter

-1 including unnecessary code that causes a side effect like a compile error or console output

1. StringRotation

(a) General Problem: Write the findNumberOfRotations method of the StringRotation class.

Refined Problem: Traverse through the rotation string and check for equality with the base string.

Algorithm:

• If the lengths of the strings are different, return -1.

• Write a loop that will traverse the rotation string one letter at a time.

• Create a substring that combines two parts of the rotation string.

• The first part is a substring that starts at position i.

• The second part is a substring that starts at position 0 up to position i-1.

• If that substring is equal to the base string, return i.

• Return -1 if the loop completes without having equal strings.

(b) General Problem: Write the isReverseRotation method of the StringRotation class.

Refined Problem: Reverse the rotation string and determine if it is a rotation of the base string.

Algorithm:

• If the lengths of the strings are different, return false.

• Write a loop that will traverse the rotation string one letter at a time.

• Create a substring that combines two parts of a string.

• The first part is the current letter of the base string.

• The second part is the built reverse string.

• Call the numberOfRotations method passing the two strings as parameters.

• If the result is -1, return false; otherwise return true.

Java Code

Image

Common Errors:

• Not traversing the string correctly or failing to access each element as needed.

• Incorrectly calling string methods.

• Not returning a value.

Scoring Guidelines: StringRotation

Image

Sample Driver:

There are many ways to write these methods. Maybe yours is a bit different from the sample solutions shown here and you are not sure if it works. Here is a sample driver program. Running it will let you see if your code works and will help you debug it if it does not.

Copy RotationDriver into your IDE along with the complete StringRotation class methods (your solution).

Image

Image

Image

2. SummerSpecial

General Problem: Write the SummerSpecial class.

Refined Problem: Create the SummerSpecial class with two instance variables and one two-parameter constructor. The two methods isSet and getPrice will need to be defined.

Algorithm:

• Write a class header for SummerSpecial.

• Declare two instance variables of type FurnitureItem to store the values of the furniture items.

• Write a constructor with two parameters of type FurnitureItem that represent two furniture items and assign the parameters to the corresponding instance variables.

• Write method isSet.

• Determine the last five characters of each item.

• Test the last five characters of each item for equality.

• Write method getPrice.

• Determine which furniture item is the most expensive and which furniture item is the least expensive.

• Call isSet to determine if the two pieces are a set.

• Based on the result of that call, calculate the price of the items.

Java Code:

Image

Image

Common Errors:

• The instance variables must be declared private.

• Strings must be compared using .equals or .compareTo methods.

• The substring method must be used to obtain the last 5 characters in the string.

Image

Sample Driver:

There are many ways to write these methods. Maybe yours is a bit different from the sample solutions shown here and you are not sure if it works. Here is a sample driver program. Running it will let you see if your code works and will help you debug it if it does not.

Copy SummerDriver and FurnitureItem into your IDE along with the complete SummerSpecial class (your solution).

Image

3. GPSRouter

(a) General Problem: Write the maxMileage method of the GPSRouter class.

Refined Problem: Traverse through the ArrayList routes to find the element with the highest mileage.

Algorithm:

• If the size of the ArrayList routes is 0, then return null.

• Create a temporary variable highest of type Route and initialize it to the 0th element of routes.

• Write a loop to traverse the routes ArrayList.

• Compare each element with highest.

• If a larger value is found, replace highest with that value.

• Return highest.

(b) General Problem: Write the addMiles method of the GPSRouter class.

Refined Problem: Traverse through the ArrayList routes looking at the names of the routes. If the name is already an element of routes, add the mileage to the existing Route element, otherwise create and add a new Route element to the routes ArrayList.

Algorithm:

• Write a loop to traverse the routes ArrayList.

• For each element in routes, compare the route name to the parameter that was passed.

• If the route name matches, add the miles that were passed as a parameter to the currently stored mileage in routes.

• If the route name was not found, create a new Route object and add that element to routes.

Java Code

Image

Note: the code fragment in both part a and part b

Image

Common Errors:

• Not traversing the ArrayList correctly or failing to access each element as needed.

• Incorrectly calling Route methods.

• Strings must be compared using .equals or .compareTo methods.

Image

Sample Driver:

There are many ways to write these methods. Maybe yours is a bit different from the sample solutions shown here and you are not sure if it works. Here is a sample driver program. Running it will let you see if your code works and will help you debug it if it does not.

Copy GPSDriver and Route into your IDE along with the complete GPSRouter class methods (your solution).

Image

Image

4. Coin Collector

(a) General Problem: Complete the CoinCollectionTools class constructor.

Refined Problem: Instantiate the instance variable coinBox as a new array of the size specified by the parameters. Traverse the array filling every cell with a Coin object instantiated with country = the country parameter, year = 0, and coinType = 0.

Algorithm:

• Instantiate coinBox as a new array of Coin objects with dimensions [rows][columns].

• Outer loop: traverse the rows of the array.

• Inner loop: traverse the columns of the array.

• Instantiate a new Coin object, passing parameters (country, 0, 0).

Java Code:

Image

Common Errors:

• If you look above the constructor in the code for the class, you will see that the coinBox has been declared as an instance variable. If you write:

int[][] coinBox = new int[rows][columns];

then you are declaring a different array named coinBox that exists only within the constructor. The instance variable coinBox has not been instantiated.

Java Code Alternate Solution:

If you read the whole problem before starting to code, you might have noticed that the other two parts work in column-major order. You can write this in column-major order also. Since you are filling every cell with the same information, it doesn’t make any difference.

Image

(b) General Problem: Complete the fillCoinBox method.

Refined Problem: The parameter myCoins is an ArrayList of Coin objects in order by year minted. Assign them to the coinBox grid in column-major order.

Algorithm:

• Create a count variable.

• Loop through all of the Coin objects in myCoins using variable count as the loop counter.

• Update the row and column variables based on count.

• Get the next Coin object from the ArrayList, and place it in the coinBox location specified by the row and column variables.

• Increment the count variable.

• Return the completed coinBox.

Java Code:

Image

Java Code Alternate Solution #1:

You may not have thought of using % and / to keep track of column and row. Here’s another way to do it.

Image

Java Code Alternate Solution #2:

This solution bases its loops on the grid, rather than the ArrayList.

Image

Common Errors:

• Do not count on the fact that you can fill the entire grid. It is tempting to write nested for loops that traverse the whole grid, but if there are fewer Coin objects in the ArrayList than elements in the grid, your program will terminate with an IndexOutOfBoundsException.

• It is common to write the row and column loops in the wrong order. In column-major order, columns vary slower than rows (we do all the rows before we change columns), so the column loop is the outer loop. In row-major order, the row loop is the outer loop.

• Even though we are filling our array in column-major order, the syntax for specifying the element we want to fill is coinBox[row][column], not the other way around.

• If you used remove instead of get when accessing the Coin objects in the ArrayList, you modified the list and that’s not allowed. It’s called destruction of persistent data and may be penalized.

• In the solutions that loop through the grid (Alternates #2 and #3), be careful not to use incorrect notation for the end conditions. In general, the number of rows is arrayName.length and the number of columns is arrayName[row].length. When processing in column-major order, the loop that varies the column is the outer loop. We cannot use the loop variable row as the array index when finding the length of a column, because it does not exist outside of the inner loop. Since this is not a ragged array, it is safe to use [0] as our index.

(c) General Problem: Complete the fillCoinTypeList method.

Refined Problem: Given a coinBox as created by part (a) and filled in part (b), create a list that contains Coins in order by coin type (1—6). If Coins are retrieved from the coinBox in column-major order, they will already be in order by year.

Algorithm:

• Loop 1: Complete the inner loops 6 times, once for each coin type 1—6.

• Loop 2: Loop through the columns.

• Loop 3: Loop through the rows.

• If the Coin object at the row-column location specified by the loop counters of loops 2 and 3 matches the coinType specified from the loop counter of loop 1:

• Add the Coin object to the ArrayList.

• Return the ArrayList of Coin objects.

Java Code:

Image

Common Errors:

• You should not create a new Coin object to add to the myCoins list. The Coin object already exists in the array.

• Do not worry about the default Coins added in the constructor. Since they have a coinType of 0, they will be ignored.

Image

Sample Driver:

There are many ways to write these methods. Maybe yours is a bit different from our sample solutions and you are not sure if it works. Here is a sample driver program. Running it will let you see if your code works, and will help you debug it if it does not.

CopyCoinCollectionToolsDriver into your IDE along with the complete Coin and CoinCollectionTools classes (including your solutions). You will also need to add this import statement as the first line in your CoinCollectionTools class: import java.util.ArrayList;

Image