AP Computer Science A Practice Exam 2

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

AP Computer Science A Practice Exam 2
STEP 5 Building Your Test-Taking Confidence

Multiple-Choice Questions

ANSWER SHEET

Image

AP Computer Science A Practice Exam 2

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 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 code segment.

Image

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

Image

2. Consider the following code segment.

Image

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

(A) [Salad, Empanadas, Sushi, Curry]

(B) [Hummus, Salad, Empanadas, Sushi, Curry]

(C) [Hummus, Soup, Sushi, Empanadas, Salad, Curry]

(D) [Soup, Empanadas, Sushi, Curry]

(E) [Hummus, Sushi, Salad, Curry]

3. Consider the following output.

Image

Which of the following code segments will produce this output?

(A) I only

(B) II only

(C) I and II only

(D) II and III only

(E) I, II, and III

Questions 4—5 refer to the following two classes.

Image

4. Assume the following declaration appears in a client program.

Boat yacht = new Boat(20);

What is printed as a result of executing the call yacht.start()?

Image

5. Which of the following statements results in a compile-time error?

Image

(A) I only

(B) II only

(C) III only

(D) II and III only

(E) None of these options will result in a compile-time error.

6. Consider the following recursive method.

Image

What value is returned as a result of the call weird(3) ?

(A) -2

(B) 3

(C) 4

(D) 6

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

7. Consider the following method.

Image

The method verifyValues is intended to return true if the array passed as a parameter is in ascending order (least to greatest), and false otherwise.

Which of the following lines of code could replace /* missing code */ so the method works as intended?

Image

8. Consider the following code segment.

Image

What is the value of after the code segment has been executed?

(A) 0

(B) 9

(C) 21

(D) 36

(E) 72

9. Consider the following method.

Image

Consider the following code segment.

Image

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

(A) 1

(B) 3

(C) 4

(D) 5

(E) 6

10. Consider the following code segment.

Image

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

(A) 0

(B) 1

(C) 1073741823

(D) Nothing will be printed. The code segment will terminate without error.

(E) Nothing will be printed. The first loop is an infinite loop.

11. Consider the following class.

Image

Consider the following code segment that appears in another class.

Image

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

(A) Ford Spectre

(B) Ford Fusion

(C) Kia Spectre

(D) Toyota Corolla

(E) Toyota Spectre

12. Given the String declaration

String course = “AP Computer Science A”;

What value is returned by the call course.indexOf(“e”)?

(A) 9

(B) 10

(C) 18

(D) 9, 15, 18

(E) 10, 16, 19

13. Consider the code segment.

Image

Which segment could be used to replace the segment above and work as intended?

Image

14. A bank will approve a loan for any customer who fulfills one or more of the following requirements:

• Has a credit score ≥ 640

• Has a cosigner for the loan

• Has a credit score ≥ 590 and has collateral

Which of the following methods will properly evaluate the customer’s eligibility for a loan?

Image

(A) I only

(B) II only

(C) III only

(D) I and III only

(E) II and III only

15. Consider the following method.

Image

What is returned by the call mixItUp("AP", "CS")?

(A) "APAP"

(B) "APCSAP"

(C) "APAPAP"

(D) "APCSCS"

(E) "APAPAPAP"

16. Assume that planets has been a correctly instantiated and initialized array that contains the names of the planets. Which of the following code segments will reverse the order of the elements in planets?

Image

17. Consider the program segment.

Image

How many times will “AP Computer Science A Rocks!!!” be printed?

(A) stop — start - 1

(B) stop - start

(C) stop — start + 1

(D) stop -1

(E) stop

18. Consider the following code segment.

Image

What are the possible values that could be printed to the console?

(A) Any real number from 4 to 10 (not including 10)

(B) Any integer from 5 to 10 (inclusive)

(C) Any integer from 20 to 49 (inclusive)

(D) Any integer from 25 to 54 (inclusive)

(E) Any real number from 30 to 50 (inclusive)

19. Consider the following code segment.

Image

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

Image

20. Consider the following incomplete method.

Image

The following table shows several examples of the desired result of a call to validation.

Image

Which of the following code segments should replace /* missing code */ to produce the desired return values?

(A) return x > y;

(B) return (x % y) > 1

(C) return (x + y) % 2 == 0

(D) return (x + y) % x == y;

(E) return (x + y) % 2 > (y + y) % 2;

21. Consider thefollowing method that is intended to remove all Strings from words that are less than six letters long. The line numbers are used for reference only.

Image

Which line of code contains an error that prevents letterCountCheck from working as intended?

(A) Line 1

(B) Line 2

(C) Line 3

(D) Line 4

(E) Line 5

22. Consider the following recursive method.

Image

What is printed as a result of executing the call wackyOutput("APCS")?

(A) PC

(B) SCPA

(C) SCSPCS

(D) PCSCSS

(E) SCSPCSAPCS

23. Consider the following method.

Image

Which of the following methods will give the exact same results as calculate?

Image

(A) I only

(B) II only

(C) III only

(D) I and II only

(E) I, II, and III

24. Consider the following class declaration.

Image

The following code segment is executed in the main method.

Image

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

(A) 0.0

(B) 3.0

(C) 12.0

(D) 19.0

(E) 27.5

25. Consider the following method.

Image

What is the value of num after executing the following code statement?

Image

(A) 6

(B) 7

(C) 10

(D) Nothing is returned. Modulus by 0 causes an ArithmeticException.

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

26. Consider the following method which implements an Insertion Sort algorithm.

Image

Consider the following array which will be passed to the sortIt method.

Image

What does the array contain after the 3rd time through the outer loop (i == 3)?

Image

27. Consider the following class.

Image

Consider the following class.

Image

Which of the following is a correct implementation of the contains method?

Image

28. Consider thefollowing method.

Image

Assume that ArrayList names has been correctly instantiated and populated with the following entries.

Image

What are the values of the ArrayList returned by the call rearrange(names)?

Image

29. Consider the following code segment.

Image

What will be printed as a result of executing the code segment?

Image

30. Consider the following code segment.

Image

What is the value of newGrid[2][1] as a result of executing the code segment?

(A) 3

(B) 4

(C) 5

(D) 7

(E) Nothing. There is an ArrayIndexOutOfBoundsException.

31. Consider the following code segment.

Image

Which of the following shows the values in grid after executing the code segment?

Image

32. What can the following method best be described as?

Image

(A) Insertion Sort

(B) Selection Sort

(C) Binary Search

(D) Merge Sort

(E) Sequential Search

33. The following incomplete code is intended to count the number of times the letter key is found in phrase.

Image

Which can be used to replace /* missing code */ so that countOccurrences works as intended?

Image

34. Assume str1 and str2 are correctly initialized String variables. Which statement correctly prints the values of str1 and str2 in alphabetical order?

Image

35. Assume names is a String array. Which statement correctly chooses a random element from the array?

Image

36. Assume that the variable declarations have been made.

Image

Which will evaluate to true?

Image

(A) I only

(B) II only

(C) III only

(D) I and III only

(E) I, II, and III

Questions 37—38 refer to the following class.

Image

Consider the following code segment.

Image

37. Which of the following calls returns the value 20?

(A) c1.getX()

(B) c1.getY()

(C) c2.getX()

(D) c2.getY()

(E) c3.getX()

38. Which of the following calls returns the value 30?

(A) c1.getX()

(B) c2.getX()

(C) c3.getX()

(D) All of the above

(E) None of the above

Questions 39—40 refer to the following classes.

Consider the following class declarations.

Image

39. Assume that ArrayList list has been correctly instantiated and populated with Building objects.

Which of the following code segments will result in the square feet in each building being printed?

Image

(A) I and IV only

(B) I and V only

(C) II and IV only

(D) III and IV only

(E) III and V only

40. Consider the following code segment.

Image

What will be printed by the following code segment?

Image

STOP. End of Part I.

AP Computer Science A Practice Exam 2

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 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. In the seventeenth century, Location Numerals were invented as a new way to represent numbers. Location Numerals have a lot in common with the binary number system we use today, except that in Location Numerals, successive letters of the alphabet are used to represent the powers of two, starting with A = 20 all the way to Z = 225.

To represent a given number as a Location Numeral (LN), the number is expressed as the sum of powers of two with each power of two replaced by its corresponding letter.

Image

Let’s consider the decimal number 19.

• 19 can be expressed as a sum of powers of 2 like this: 16 + 2 + 1 = 24 + 21 + 20.

• We can covert 19 to LN notation by choosing the letters that correspond with the powers of 2: EBA.

Here are a few more examples.

Image

A partial LocationNumeral class is shown below.

Image

Image

(a) Write the method getLetterValue that returns the numerical value of a single LN letter.

The value of each LN letter is equal to 2 raised to the power of the letter’s position in the alphabet string.

For example, if passed the letter “E”, the method will return 16, which is 24.

Image

(b) Write the method getDecimalValue that takes a Location Numeral and returns its decimal value.

For example, if passed the String “ECA”, the method will add the decimal values of E, C, and A and return the result. In this case: 16 + 4 + 1 = 21.

You may assume that getLetterValue works as intended, regardless of what you wrote in part (a).

Image

(c) Write the method buildLocationNumeral that takes a decimal value and returns the Location Numeral representation of that decimal value.

For example, if passed the value 43, the method will return the String “FDBA”, which represents the sum 32 + 8 + 2 + 1.

Image

2. A quadratic function is a polynomial of degree 2, which can be written in the form y = ax2 + bx + c, where a, b, and c represent real numbers and a ≠ 0. The x-intercepts, or roots, of a quadratic function can be found by using the quadratic formula.

Image

The value of the discriminant b2 — 4ac determines whether the roots are real or non-real (imaginary). If the discriminant > 0, the function has 2 real roots. If the discriminant = 0 the function has 1 real root, and if the discriminant < 0, it has imaginary (0 real) roots. Examples are shown in the table.

Image

Assume that the following code segment appears in a class other than Quadratic. The code segment shows a sample of using the Quadratic class to represent the three equations shown in the table.

Image

Write the Quadratic class. Your implementation must include a constructor that has three double parameters that represent a, b, and c, in that order. You may assume that the value of a is not zero. It must also include a method getDiscriminant that calculates and returns the value of the discriminant, a method root1 and a method root2 that will calculate the possible two roots of the equation. Your class must produce the indicated results when invoked by the code segment given above.

3. A printing factory maintains many printing machines that hold rolls of paper.

Image

The factory keeps track of its printing machines in array machines, and it keeps track of its paper supply in two lists: newRolls to hold fresh rolls and usedRolls to hold the remnants taken off the machines when they no longer hold enough paper to be usable. At the beginning of the day, usedRolls is emptied of all paper remnants and newRolls is refilled. When newRolls no longer has enough rolls available to refill all the machines, the factory must shut down for the day until its supplies are restocked. At that time, the amount of paper used for the day is calculated.

A partial PrintingFactory class is shown below.

Image

(a) Write the replacePaper method of the Machine class. This method returns the nearly empty PaperRoll and replaces it with the PaperRoll passed as a parameter.

Image

(b) Write the replacePaperRolls method of the PrintingFactory class.

At the end of each job cycle, each Machine object in machines is examined to see if its PaperRoll needs replacing. A PaperRoll is replaced when it has less than 4 meters of paper remaining. The used roll is added to the usedRolls list, while a new roll is removed from the newRolls list.

Image

(c) Write the getPaperUsed method of the PrintingFactory class.

At the end of the day, the factory calculates how much paper has been used by adding up the amount of paper used from all the rolls in the usedRolls list and all the rolls still in the machines. A brand-new paper roll has 1000 meters of paper.

Example

The tables below show the status of the factory at the end of the day.

Image

Total used: 100.0 + 750.0 + 850.0 + 996.5 + 998.0 + 998.5 + 997.0 = 5690.0 meters

Complete the method getPaperUsed.

Image

4. A hex grid is a type of two-dimensional (2D) map used by many games to represent the area that tokens, ships, robots, or other types of game pieces can move around on.

The GamePiece class is intended to represent the various game pieces required to play different games on the HexGrid. The implementation of the GamePiece class is not shown. You may construct a GamePiece object with a no-argument constructor.

A hex grid is represented in the HexGrid class by a 2D array of GamePiece objects. The coordinates of a GamePiece represent its position on the HexGrid as shown in the following diagram. Many of the hex cells in the HexGrid will not be occupied by any GamePiece and are therefore null.

The rows in a HexGrid are in a staggered horizontal pattern where hexes in even columns rise higher than hexes in odd-numbered columns. The columns in a HexGrid always appear vertically aligned regardless of the value of the row.

The following is a representation of a HexGrid object that contains several GamePiece objects at specified locations in the HexGrid. The row and column of each GamePiece are given.

Image

Image

Image

(a) Write the method getGamePieceCount. The method returns the number of GamePiece objects in the hex grid.

Image

(b) Write the method isAbove. The method returns an ArrayList of GamePiece objects that are located “above” the GamePiece in the row and column specified in the parameters. “Above” is defined as in the same column but with a lower row number than the specified location. In the diagram below, letters represent GamePiece objects. The objects may appear in any order in the ArrayList.

• If the method is called with the row and column of C, an ArrayList containing A and B will be returned.

• If the method is called with the row and column of F, an ArrayList containing E will be returned.

• If the method is called with the row and column of E, an empty ArrayList is returned.

• If the method is called with the row and column of an empty cell, null is returned.

Image

Image

(c) Write the addRandom method. This method takes a parameter that represents the number of GamePiece objects to be added to the grid at random locations. GamePiece objects can only be added to locations that are currently empty (null). If there are insufficient empty cells to complete the requested additions, no GamePiece objects will be added and the method will return false. If the additions are successful, the method will return true.

You may assume that getGamePieceCount works as intended, regardless of what you wrote in part (a). You must use getGamePieceCount appropriately in order to receive full credit for part (c).

Image

STOP. End of Part II.

Practice Exam 2 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.

• The outer loop will start at h = 5 and then, on successive iterations, h = 3 and h = 1.

• The inner loop will start at k = 0, then 1 and 2.

• The if statement will print h + k only if their sum is even (since % 2 = 0 is true only for even numbers).

• Since h is always odd, h + k will be even only when k is also odd. That only happens once per inner loop, when k = 1. Adding h and k, we get 5 + 1 = 6, 3 + 1 = 4, and 1 + 1 = 2, so 6 4 2 is printed.

2. The answer is A.

• Let’s picture our ArrayList as a table. After the first three add statements we have:

Image

• The set statement changes element 1:

Image

• Add at index 0 gives us:

Image

• Remove the element at index 1:

Image

• And finally, add “Curry” to the end of the list:

Image

3. The answer is B.

• Option I is incorrect. The outer loop begins at i = letters.length. Remember that the elements of an array start at index = 0 and end at index = length − 1. Starting the loop at i = letters.length will result in an ArrayIndexOutOfBoundsException.

• Option II is correct. The outer loop takes each letter from the string in turn, and the inner loop prints it four times, as long as it is not an "S".

• Option III is incorrect. It correctly traverses each element in the array, but then only prints each element once, not four times.

4. The answer is D.

• The constructor call creates a new Boat and the super call sets the fuel variable in the Vehicle class to 20.

• The call to the Boat class start method:

• begins by calling the Vehicle class start method, which prints "Vroom",

• then calls useFuel, which calls the useFuel method in the Boat class, which calls the Vehicle class changeFuel method, which subtracts 2 from the fuel variable, and

• finally, the start method prints "Remaining Fuel" followed by the value in the Vehicle class fuel variable, which is now 18.

5. The answer is C.

• The type on the left side of the assignment statement can be the same type or a super type of the object constructed on the right side of the assignment statement. The object constructed should have an is-a relationship with the declared type.

• Option I is correct. A Boat is-a Boat.

• Option II is correct. A Boat is-a Vehicle.

• Option III is incorrect. Vehicle is a super class of Boat. A Boat is a Vehicle, but a Vehicle doesn’t have to be a Boat. The super class must be on the left side of the assignment statement.

6. The answer is E.

• This is a recursive method. The first call results in:

Image

A recursive method must approach the base case or it will infinitely recurse (until the Stack overflows). The call to weird(3) calls weird(3) again, which will call weird(3) again, which will call weird(3) again.…

7. The answer is D.

• It is important to notice that the for loop is traversing the array from the greatest index to the least. The array is correct if every element is greater than or equal to the one before it.

• We will return true if we traverse the entire array without finding an exception. If we find an exception, we return false, so we are looking for that exception, or values[index − 1] > values[index].

• Option A is incorrect because of the =.

• Note that since we must not use an index that is out of bounds, we can immediately eliminate any answer that accesses values[index + 1] which eliminates options B and E.

8. The answer is D.

• The first nested loop initializes all the values in the array in row-major order. The first value entered is 0, then 1, 2, etc. After these loops terminate, the matrix looks like this:

Image

• The second nested loop (for-each loops this time) traverses the array and adds all the values into the sum variable. 0 + 1 + 2 + … + 8 = 36.

9. The answer is C.

• doStuff is going to loop through the array, checking to see if each item is the same as the item before it. If it is, the values of index, maxCounter, and counter all change. If it is not, only counter changes.

• Begin by setting index = 0; maxCounter = 1; counter = 1; and noting that numberArray.length() = 5.

• First iteration: k = 1, enter the loop with index = 0; maxCounter = 1; counter = 1;

• Item 1 = item 0, execute the if clause

• counter <= maxCounter, execute the if clause

• maxCounter = 1; index = 1

• counter = 2

• Second iteration: k = 2, enter the loop with index = 1; maxCounter = 1; counter = 2;

• Item 2 != item 1, execute the else clause

• counter = 1

• Third iteration: k = 3, enter the loop with index = 1; maxCounter = 1; counter = 1;

• Item 3 = item 2, execute the if clause

• counter <= maxCounter, execute the if clause

• maxCounter = 1; index = 3

• counter = 2

• Fourth iteration: k = 4, enter the loop with index = 3; maxCounter = 1; counter = 2;

• Item 4 != item 3, execute the else clause

• counter = 1

• Fifth iteration: k = 5, which fails the condition and the loop exits.

• index = 3, numberArray[3] = 4 is returned and printed.

10. The answer D.

• Integer.MAX_VALUE is a large number, but repeatedly dividing by 2 will eventually result in an answer of 0 and the loop will terminate. Remember that this is integer division. Each quotient will be truncated to an integer value. There will be no decimal part.

• In the second loop, the initial condition sets i = 0, which immediately fails the condition. The loop never executes, so nothing is printed, but the code segment terminates successfully.

11. The answer is A.

• myCar is instantiated as a reference variable pointing to an Automobile object with instance variables make = "Ford" and model = "Fusion".

Image

• companyCar is instantiated as a reference variable pointing to an Automobile object with instance variables make = "Toyota" and model = "Corolla".

Image

• The statement companyCar = myCar reassigns the companyCar reference variable to point to the same object as the myCar variable. They are now aliases of each other. The original companyCar object is now inaccessible (unless yet another variable we don’t know about points to it).

Image

• The next statement instantiates a brand-new Automobile object with make = "Kia" and model = "Spectre". It sets the myCar reference variable to point to this new object. This does not change the companyCar variable.

• The companyCar variable still points to the object with instance variables make = "Ford" and model = "Fusion".

Image

• So we print companyCar’s make, which is "Ford" followed by myCar’s model, which is "Spectre".

12. The answer is A.

• The indexOf(str) method returns the index of the first occurrence or -1 if not found.

• The index position begins counting at 0. “e” is found at position 9.

13. The answer is C.

• Both of the conditions in the original segment add 1 or 2, which is value, to count.

• The conditions can be combined using an || statement.

14. The answer is D.

• Option I is correct. Note that the final condition, (credit >= 590 && coll), doesn’t have to be in parentheses. Since AND has a higher priority than OR, it would be executed first, even without the parentheses. However, the parentheses make the code clearer, and that is always our goal.

• Option II is incorrect. While it seems reasonable at first glance, De Morgan’s theorem tells us we can’t just distribute the !. We also have to change OR to AND.

• Option III is correct. As soon as a condition evaluates to true, the method will return and no more statements will be executed. Therefore no else clauses are required. The method will return false only if none of the conditions are true.

15. The answer is C.

• To answer this problem, you need to understand that String objects are immutable (the only other immutable objects in our Java subset are Integer and Double.

• When the method begins, entry1 = "AP" and entry2 = "CS".

• Then the assignment statement reassigns entry2 so that both variables now refer to the String object containing "AP".

• When we execute the next statement, entry1 = entry1 + entry2, we would expect that to change for both variables, since they both reference the same object, but String objects don’t work that way. Whenever a string is modified, a new String object is created to hold the new value. So now, entry1 references "APAP" but entry2 still references "AP".

• We put those together, and “APAPAP” is returned.

16. The answer is E.

• Remember, we only need to find one error to eliminate an option.

• Option A is incorrect. index starts in the middle of the array and goes down to zero. We swap the item at index with the item at index + 1. We are never going to address the upper half of the array.

• Option B is incorrect. The swap code is incomplete. We put planets[index] into s, but then never use s.

• Option C is incorrect. It’s OK to use another array, but this code forgets to switch the order when it moves the elements into the new array. The new array is identical to the old one.

• Option D is incorrect. At first glance, there’s no obvious error. The swap code looks correct. Although planets.length − 1 − index seems a bit complex, a few examples will show us that it does, indeed, give the element that should be swapped with the element at index: 0 Image 7 − 0 = 7, 1 Image 7 − 1 = 6, 2 Image 7 − 2 = 5, 3 Image 7 − 3 = 4, and so on. The trouble with this option is that “and so on” part. It swaps all the pairs and then continues on to swap them all again. After completing the four swaps listed above, we are done and we should stop.

• Option E is correct. The code is the same as option D, except it stops after swapping half the elements. The other half were the partners in those first swaps, so now everything is where it should be.

17. The answer is C.

• The loop begins at whatever value is stored in start and will continue until the value stored in stop is reached.

• Try substituting start = 1 and stop = 5. The loop will execute 5 times.

• Substituting 1 and 5 into the answer options, A, B, and D are eliminated.

• Choosing different values for start and stop such as 2 and 10 will result in option C.

18. The answer is B.

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

Image

• high − low + 1 = 30, low = 20, so high = 49

• After the first statement, num is an integer between 20 and 49 (inclusive).

• In the second statement, we add 5 to num. Now num is between 25 and 54 (inclusive).

• In the third statement we divide by 5, remembering integer division. Now num is between 5 and 10 (inclusive).

19. The answer is A.

• This loop takes pieces of the String "computer" and places them in an ArrayList of String objects.

• The loop starts at index k = 0, and adds the word.substring(0), or the entire word, to the ArrayList. The first element of the ArrayList is "computer".

• Then k is incremented by the k++ inside the loop, k = 1, and immediately incremented again by the instruction in the loop header, k = 2. It is bad programming style to change a loop index inside the loop, but we need to be able to read code, even if it is poorly written.

• The second iteration of the loop is k = 2, and we add word.substring(2) or "mputer" to the ArrayList.

• We increment k twice and add word.substring(4) or "uter".

• We increment k twice and add word.substring(6) or "er".

• We increment k twice and fail the loop condition. The loop terminates and the ArrayList is printed.

20. The answer is E.

• We need to plug the values of x and y into the given statements to see if they always generate the correct return value.

• Option A is incorrect. 3 > 6 is false, but should be true.

• Option B is incorrect. 1 % 0 will fail with a division by zero error.

• Option C is incorrect. (1 + 0) % 2 == 0 is false, but should be true.

• Option D is incorrect. (3 + 6) % 3 == 6 is false, but should be true.

• Option E works for all the given values.

21. The answer is B.

• The loop will continue until numWord = words.size(), which will cause an ArrayIndexOutOfBoundsException.

• Notice that numWord is only incremented if nothing is removed from the ArrayList. That is correct because, if something is removed, the indices of the elements after that element will change. If we increment numWord each time, we will skip elements.

22. The answer is C.

• This is an especially difficult example of recursion because the recursive call is not the last thing in the method. It’s also not the first thing in the method. Notice that the print happens after the call. So each iteration of the method will print one letter less than its parameter.

• 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.

Image

Remember that the returns are read bottom to top, so the output is "SCSPCS" in that order.

• Note that “S”.substring(1,1) is not an error. It returns the empty string.

23. The answer is D.

• Option I is correct. It uses De Morgan’s theorem to modify the boolean condition.

Image

• Option II is correct. It tests the two parts of the condition separately. If either fails, it returns "Numbers are not valid".

• Option III is incorrect. If num1 is a positive number and num2 is a negative number, but the absolute value of num2 < num1 (num1 = 5 and num2 = -2, for example), option III will return "Numbers are valid" although clearly both numbers are not >= 0.

24. The answer is A.

• test1 references a TestClass object with value = 9.0 and test2 references a TestClass object with value = 17.5.

Image

• After the addValue and reduceValue calls, our objects look like this:

Image

• The assignment statement changes test2 to reference the same object as test1.

Image

• At this point, the object with value = 19.0 is inaccessible (unless another reference variable we don’t know about is pointing to it). The next time Java does garbage collection, it will be deleted.

• The next reduceValue call changes our object to this:

Image

• The getValue statements in the next line get the same value, as test1 and test2 are pointing to the same object. 0.0 + 0.0 = 0.0.

25. The answer is B.

• 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.

• Be very careful to get the order of num1 and num2 correct in the modulus operation and the parameters correct in the recursive call.

• guess(3, 17) = guess(17, 3) + 3 = 4 + 3 = 7 which gives us our final answer.

• guess(17, 3) = guess(3, 2) + 2 = 2 + 2 = 4

• guess(3, 2) = guess(2, 1) + 1 = 1 + 1 = 2

• guess(2,1) Base case! return 3/2 = 1 (integer division)

26. The answer is B.

This method implements a standard insertion sort. In this sort, each item is taken in turn and placed in its correct position among the items to its left (with lower indices).

• The first time through the loop, i = 1, the algorithm looks at the first two values {4, 3…} and inserts the 3 in the right place {3, 4…}. The rest of the array is untouched.

• The second time through, i = 2, the algorithm looks at the first three values {3, 4, 7…}. Since the 7 is already in the right place, no changes are made.

• The third time through, i = 3, the algorithm looks at the first four values {3, 4, 7, 6…} and inserts the 6 in the right place {3, 4, 6, 7…}. Our answer is {3, 4, 6, 7, 1, 5, 2}.

• If we were to continue, the final three values, {…1, 5, 2} would be inserted in their correct locations during the remaining 3 iterations of the outside loop.

Note: Answer C is the result of the third pass of a standard selection sort algorithm.

27. The answer is A.

• In order for a rectangle to contain a point, the following conditions must be true:

topLeftX < x < bottomRightX and topLeftY < y < bottomRightY

• Option A is correct. These are the exact conditions used in option A, though they are in a different order.

• Option B is incorrect because it will return true if any one of the four conditions is true.

• Options C and D are incorrect because they attempt to make invalid calls to super or Polygon methods that do not exist.

• Option E is incorrect. It is similar to option B, except that it will return true if two of the required conditions are true.

28. The answer is A.

• Let’s show the contents of the ArrayList graphically and trace the code. The method is called with this ArrayList.

Image

• The first time through the loop, i = 3. The element at index 3 is removed and added to the end of the ArrayList.

Image

• Decrement i, i = 2, which is >= 0, so execute the loop again. The element at index 2 is removed and added to the end.

Image

• Decrement i, i = 1, which is >= 0, so execute the loop again. The element at index 1 is removed and added to the end.

Image

• Decrement i, i = 0, which is >= 0, so execute the loop again. The element at index 0 is removed and added to the end.

Image

• Decrement i, i = -1, which fails the loop condition. The loop terminates and the ArrayList is returned.

29. The answer is C.

• The loop will execute while varA != 0 OR varB > 0. Another way to say that, using De Morgan’s theorem, is that the loop will stop executing when varA == 0 AND varB <= 0.

• The only answer that fits that condition is C: varA = 0 and varB = -4.

• Instead of thinking through the logic, we could trace the execution of the loop, but it’s a lot of work. Here’s a table of the values of varA and varB at the end of every iteration of the loop until the loop terminates.

Image

30. The answer is C.

• The nested loops go through grid in row-major order, but assign into newGrid in column-major order. (Notice that newGrid is instantiated with its number of rows equal to the grid’s number of columns and its number of columns equal to the grid’s number of rows.) After executing the loops, newGrid looks like this:

Image

• newGrid [2][1] = 5

31. The answer is E.

• The nested loops traverse the entire array. Each time through, the three assignment statements are executed. The key to the problem is the order in which these statements are executed. We need to pay attention to which values will overwrite previously assigned values.

• On entering the loops, our array looks like this:

Image

• We will execute the outer loop three times, and for each of those three times, we will execute the inner loop three times.

• The first iteration of both loops, we are changing element [0][0].

• The first statement makes it a 1.

• Note that this statement changes the array in row-major order.

• The second statement makes it a 2.

• Note that this statement changes the array in column-major order.

• The third statement makes it a 3, so it will remain a 3.

• Note that this statement only changes the diagonals.

• Completing the first cycle of the inner loop, the first statement assigns a 1 to [0][1] and [0][2] and the second statement assigns a 2 to [1][0] and [2][0]. The third statement repeatedly sets [0][0] to 3, and since that statement is last, it will remain a 3.

Image

• The next cycle of the inner loop will assign a 1 to [1][0], [1][1], and [1][2]. A 2 will be assigned to [0][1], [1][1], and [2][1]. Then element [1][1] will be overwritten with a 3.

Image

• The third (and last) cycle of the inner loop will assign a 1 to [2][0], [2][1], and [2][2]. A 2 will be assigned to [0][2], [1][2], and [2][2]. Then element [2][2] will be overwritten with a 3.

Image

32. The answer is E.

• If this were a sorting algorithm, there would be only one parameter, the array to be sorted, and a sorted array would be returned, so we can eliminate the sorting algorithms. In addition, Merge Sort is recursive, and selection and insertion sorts require nested loops, neither of which appear in this code.

• Binary search repeatedly divides the remaining section of the array in half. There’s no code that does anything like that. This is not a binary search.

• This code goes through the array one step at a time in order. This is a sequential search algorithm.

33. The answer is E.

• Each pass of the loop needs to check one letter to see if it is the desired key.

• The substring(i, i+1) method is used to look at one letter at a time.

• Each time the letter matches the key, then count is incremented by 1.

34. The answer is D.

• The compareTo(other) method returns 0 if the string object is less than other (which means it comes first alphabetically)

• Strings cannot be compared using ==, < , or > operators.

35. The answer is D.

• Math.random() doesn't take any parameter, so options A and B can be eliminated.

• Math.random() returns a value greater than or equal to 0.0 and less than 1.0.

• Once the random double is returned, it must be multiplied by the size of the array and then cast into an integer.

36. The answer is D.

• Only I and III evaluate to true.

37. The answer is D.

• This question is explained along with question 38.

38. The answer is D.

• We will solve questions 37 and 38 together by diagramming the objects and reference variables.

• The first three assignment statements give us:

Image

• c3.setX(c2.getY()); results in:

Image

• c3 = c2; results in:

Image

• c3.setY(c2.getX()); results in:

Image

• c2.setX(c1.getX()); results in:

Image

• Question 37: Both c2.getY() and c3.getY() return 20, but only c2.getY() is an option.

• Question 38: c1.getX(), c2.getX(), and c3.getX() all return 30.

39. The answer is E.

• Option I is incorrect. Among other errors, getSqFeet does not take a parameter.

• Option II is incorrect. Square brackets are used to access elements of arrays, but not of ArrayLists.

• Option III is correct.

• Option IV is incorrect. list is the name of the ArrayList, not the name being used for each element of the ArrayList.

• Option V is correct.

40. The answer is B.

• The array holds Building objects. As long as an object is-a Building, it can go into the array.

• The runtime environment will look at the type of the object and call the version of getSize written specifically for that object.

• list[0] is a Building so the Building class getSize will be used to generate the String for list[0].

• list[1] is a House so the House class getSize will be used to generate the String for list[1].

• list[2] references the same object as list[1]. This will generate a duplicate of the list[1] response.

Part II (Free Response)

Answers and Explanations

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 local variables without first declaring them

-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 such as a compile error or console output

1. Location Numerals

(a) General Problem: Write the getLetterValue method that returns the numerical value of the given letter.

Refined Problem: Find the parameter letter’s position in the String alphabet. Return 2 raised to that power.

Algorithm:

• Use indexOf to find the position of letter in the String alphabet.

• Use Math.pow to raise 2 to the power of the position found.

• Return the result.

Java Code:

Image

(b) General Problem: Write the getDecimalValue method that takes a Location Numeral and returns its decimal equivalent.

Refined Problem: Find the value of each letter in turn and add it to running total. Return the final answer.

Algorithm:

• Create a variable to hold the running total.

• Loop through the Location Numeral String from the letter at index 0 to the end of the String.

• Isolate each letter, using substring.

• Call the method getLetterValue, passing the isolated letter.

• Add the result to the running total.

• When the loop is complete, return the total.

Java Code:

Image

Common Errors:

• Don’t end the loop at numeral.length() - 1. When you notice the expression numeral.substring(i, i + 1), you may think that the i + 1 will cause an out of bounds exception. It would if it were the first parameter in the substring, but remember that the substring will stop before the value of the second parameter, so it will not index out of bounds. If you terminate the loop at numeral.length() - 1, you will miss the last letter in the String.

• Be sure that you use the method you wrote in part (a). There is generally a penalty for duplication of code if you rewrite the function in another method. The problem usually has a hint when a previously written method is to be used. In this case, the problem says, “You may assume that getLetterValue works as intended, regardless of what you wrote in part (a).” That’s a surefire indication that you’d better use the method to solve the current problem.

(c) General Problem: Write the buildLocationNumeral method that returns the Location Numeral representation of the decimal value passed as a parameter.

Refined Problem: Determine which powers of 2 sum together to give the value of the parameter. Build the Location Numeral by determining the corresponding letters of the alphabet.

Algorithm:

• Initialize a variable to keep track of the position in the alphabet string starting at the end.

• Initialize a string variable to the empty string and add letters as appropriate.

• As long as more simplification can be done:

• Determine the value of 2current position in alphabet string.

• If the power of 2 value is larger than the current value variable

• Concatenate the corresponding alphabetic letter onto the string variable.

• Decrease the value by the power of 2.

• Decrease the position variable by 1.

• Return the final result.

Java Code:

Image

Common Errors:

• This is a tricky piece of code. There are many places where errors can sneak in. Remember that you can earn most of the points for a question even with errors or missing sections in your code.

• The key is continuously subtracting powers of 2 from value until value becomes 0 and determining the letter of the alphabet that corresponds to that power of 2.

Scoring Guidelines: Location Numerals

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.

Copy the LocationNumeralDriver into your IDE along with the LocationNumeral class (including your solutions).

• Here’s the LocationNumeralDriver:

Image

2. Quadratic

(a) General Problem: Write the Quadratic class.

Refined Problem: Create the Quadratic class with three instance variables and one three parameter constructor. The three methods getDiscriminant, getRoot1, and getRoot2 will need to be defined.

Algorithm:

• Write a class header for Quadratic.

• Declare three instance variables to store the values of a, b, and c.

• Write a constructor with three parameters that represent the coefficients of the quadratic equation and assign the parameters to the corresponding instance variables.

• Write method getDiscriminant.

• Write methods getRoot1 and getRoot2.

Java Code:

Image

Common Errors:

• The instance variables must be declared private.

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 QuadraticDriver into your IDE along with the complete Quadratic class (including your solutions). You also might want to add the toString method to your Quadratic class, which will print the quadratic equation for you.

Image

Image

3. Printing Factory

(a) General Problem: Write the replacePaper method of the Machine class.

Refined Problem: Take the new PaperRoll passed as a parameter and use it to replace the current roll. Return the used roll to the caller. Notice that this is a type of swapping and will require a temp variable.

Algorithm:

• Create a temp variable of type PaperRoll.

• Assign the machine’s PaperRoll paper to temp.

• Assign the new PaperRoll passed as a parameter to the machine’s PaperRoll.

• Return the PaperRoll in temp.

Java Code:

Image

Common Errors:

• It may seem like you want to do this:

Image

But once the return statement is executed, flow of control passes back to the calling method. The second statement will never be executed.

(b) General Problem: Write the replacePaperRolls method of the PrintingFactory class.

Refined Problem: Traverse the machines ArrayList checking for Machine object with PaperRoll objects that contain less than 4.0 meters of paper. Any PaperRoll objects containing less than 4.0 meters of paper need to be replaced. Get a new PaperRoll object from the newRolls ArrayList, and pass it to the Machine class replacePaper method. Place the returned used PaperRoll object on the usedRolls ArrayList.

Algorithm:

• Write a for-each loop to traverse the machines array.

• If the current Machine object’s PaperRoll object contains < 4.0 m of paper:

• Take a PaperRoll object off of the newRolls ArrayList.

• Call replacePaper passing the new roll as a parameter.

• replacePaper will return the old PaperRoll object; put it on the usedRolls ArrayList.

Java Code:

Image

Common Errors:

• The syntax for accessing the amount of paper remaining is complex, especially when using a for loop instead of a for-each loop. Remember that the getMeters method is not a method of the Machine class. We have to ask each Machine object for access to its PaperRoll object and then ask the PaperRoll object how much paper it has left.

Java Code Alternate Solution #1:

Use for loops instead of for-each loops.

Use just one variable for the old and new rolls.

Image

Java Code Alternate Solution #2:

Combine the statements and eliminate the variables altogether. This could also be done in the for loop version.

Image

(c) General Problem: Write the getPaperUsed method of the PrintingFactory class.

Refined Problem: The amount of paper used on each roll is 1000 minus the amount of paper remaining. First traverse the usedRolls ArrayList and add up the paper used. Next, traverse the machines array and add up the paper used. These two amounts represent the total paper used. Return the sum.

Algorithm:

• Write a for-each loop to traverse the usedRolls ArrayList.

• Add 1000 minus paper remaining on the current roll to a running sum.

• Write a for-each loop to traverse the machines array.

• Add 1000 minus paper remaining on the current machine’s roll to the same running sum.

• Return the sum.

Java Code:

Image

Java Code Alternate Solution #1:

Use for loops instead of for-each loops.

Replace sum = sum + … with sum += …

Image

Common Errors:

• Remember that ArrayLists and arrays use different syntax both to access elements and to find their total number of elements.

Java Code Alternate Solution #2:

There are other ways to compute the paper use. Here we add up all the leftover paper and then subtract the total from 1000 * the total number of rolls. This technique could be combined with the for loop version, as well as the for-each loop as shown here.

Image

Image

Image

4. Hex Grid

(a) General Problem: Write the getGamePieceCount method that counts how many GamePiece objects are located on the grid.

Refined Problem: Traverse the 2D array of GamePiece objects and count the number of cells that are not null.

Algorithm:

• Create a variable to hold the count.

• Traverse the 2D array of values using nested loops.

• Inside the loops, evaluate each cell of the grid to see if it is null. When we find an element that is not null, increment the count variable.

• Once the entire array has been traversed, the value of the count variable is returned.

Java Code:

Image

Common Errors:

• Remember that the number of rows is grid.length and the number of columns is grid[row].length or, since all columns are the same length, grid[0].length.

• The return statement has to be outside both loops.

Java Code Alternate Solution:

You can use for-each loops to traverse a 2D array.

Image

(b) General Problem: Write the isAbove method that returns the GamePiece objects that are above an object at a given location on the grid.

Refined Problem: Create an ArrayList of GamePiece objects that are above the position passed in the parameter, where “above” is defined as having the same column number and a lower row number than another object. If there is no object at the location passed in, null is returned. If there are no objects above the parameter location, an empty ArrayList is returned.

Algorithm:

• Determine whether there is a GamePiece object at the location specified. If there is not, return null.

• Create an ArrayList to hold the GamePiece objects to be returned.

• Look in the specified column and the rows from 0 up to the specified row. If any of those cells contain GamePiece objects, add them to the ArrayList.

• Return the ArrayList.

Java Code:

Image

Common Errors:

• Do not count the object itself. That means the loop must stop at r < row, not r <= row.

(c) General Problem: Write the addRandom method that adds a specified number of GamePiece objects to the grid in random locations.

Refined Problem: Check to see if there are enough blank cells to add the requested objects. If there are, use a random number generator to generate a row and column number. If the cell at that location is empty, add the object; otherwise, generate a new number. Repeat until all objects have been added.

Algorithm:

• Determine whether there are enough empty cells to hold the requested number of objects.

• If there are not, return false.

• Loop until all objects have been added.

• Generate a random int between 0 and number of rows.

• Generate a random int between 0 and number of columns.

• Check to see if that cell is free. If it is, add object and decrease number to be added by 1.

• Return true.

Note that this algorithm may take a very long time to run if the grid is large and mostly full. If that is the case, a more efficient algorithm is to put all available open spaces into a list and then choose a random element from that list.

Java Code:

Image

Scoring Guidelines: Hex Grid

Image

Scoring Worksheet

This worksheet will help you to approximate your performance on Practice Exam 2 in terms of an AP score of 1—5.

Image