0% found this document useful (0 votes)
12 views27 pages

Unit 5 Topic Questions - Writing Classes

The document contains a series of questions and code snippets related to Java programming concepts, specifically focusing on class implementations, constructors, and method functionalities. It includes multiple-choice questions about class attributes, method access levels, and expected behaviors of code segments. The questions aim to assess understanding of object-oriented programming principles in Java, including encapsulation, constructors, and method definitions.

Uploaded by

Tanisha Bentick
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views27 pages

Unit 5 Topic Questions - Writing Classes

The document contains a series of questions and code snippets related to Java programming concepts, specifically focusing on class implementations, constructors, and method functionalities. It includes multiple-choice questions about class attributes, method access levels, and expected behaviors of code segments. The questions aim to assess understanding of object-oriented programming principles in Java, including encapsulation, constructors, and method definitions.

Uploaded by

Tanisha Bentick
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

AP COMPUTER SCIENCE A Test Booklet

Unit 5 Topic Questions

1. The Car class will contain two string attributes for a car’s make and model. The class will also contain a
constructor.

public class Car


{
/* missing code */
}

Which of the following replacements for /* missing code */ is the most appropriate implementation of the
class?
public String make;
public String model;
(A) public Car(String myMake, String myModel)
{ /* implementation not shown */ }
public String make;
public String model;
(B) private Car(String myMake, String myModel)
{ /* implementation not shown */ }
private String make;
private String model;
(C) public Car(String myMake, String myModel)
{ /* implementation not shown */ }
public String make;
private String model;
(D) private Car(String myMake, String myModel)
( /* implementation not shown */ }
private String make;
private String model;
(E) private Car(String myMake, String myModel)
{ /* implementation not shown */ }

2. The Date class below will contain three int attributes for day, month, and year, a constructor, and a
setDate method. The setDate method is intended to be accessed outside the class.

public class Date


{
/* missing code */
}

Which of the following replacements for /* missing code */ is the most appropriate implementation of the
class?

AP Computer Science A Page 1 of 27


Test Booklet

Unit 5 Topic Questions

private int day;


private int month;
private int year;
(A) private Date()
{ /* implementation not shown */ }
private void setDate(int d, int m, int y)
{ /* implementation not shown */ }
private int day;
private int month;
private int year;
(B) public Date()
{ /* implementation not shown */ }
private void setDate(int d, int m, int y)
{ /* implementation not shown */ }
private int day;
private int month;
private int year;
(C) public Date()
{ /* implementation not shown */ }
public void setDate(int d, int m, int y)
{ /* implementation not shown */ }
public int day;
public int month;
public int year;
(D) private Date()
{ /* implementation not shown */ }
private void setDate(int d, int m, int y)
{ /* implementation not shown */ }
public int day;
public int month;
public int year;
(E) public Date()
{ /* implementation not shown */ }
public void setDate(int d, int m, int y)
{ /* implementation not shown */ }

3. The Player class below will contain two int attributes and a constructor. The class will also contain a
method getScore that can be accessed from outside the class.

public class Player


{
/* missing code */
}

Which of the following replacements for /* missing code */ is the most appropriate implementation of the
class?

Page 2 of 27 AP Computer Science A


Test Booklet

Unit 5 Topic Questions

private int score;


private int id;
private Player(int playerScore, int playerID)
(A) { /* implementation not shown */ }
private int getScore()
{ /* implementation not shown */ }
private int score;
private int id;
public Player(int playerScore, int playerID)
(B) { /* implementation not shown */ }
private int getScore()
{ /* implementation not shown */ }
private int score;
private int id;
public Player(int playerScore, int playerID)
(C) { /* implementation not shown */ }
public int getScore()
{ /* implementation not shown */ }
public int score;
public int id;
public Player(int playerScore, int playerID)
(D) { /* implementation not shown */ }
private int getScore()
{ /* implementation not shown */ }
public int score;
public int id;
public Player(int playerScore, int playerID)
(E) { /* implementation not shown */ }
public int getScore()
{ /* implementation not shown */ }

AP Computer Science A Page 3 of 27


Test Booklet

Unit 5 Topic Questions

4. SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.

Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are
called only when their preconditions are satisfied.
In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined
in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will
not receive full credit.

This question involves the implementation of the AddtionPattern class, which generates a number pattern.
The AdditionPattern object is constructed with two positive integer parameters, as described below.

The first positive integer parameter indicates the starting number in the pattern.
The second positive integer parameter indicates the value that is to be added to obtain each subsequent number in
the pattern.

The AdditionPattern class also supports the following methods.

currentNumber, which returns the current number in the pattern


next, which moves to the next number in the pattern
prev, which moves to the previous number in the pattern or takes no action if there is no previous number

The following table illustrates the behavior of an AdditionPattern object that is instantiated by the following
statement.

AdditionPattern plus3 = new AdditionPattern(2, 3);

Page 4 of 27 AP Computer Science A


Test Booklet

Unit 5 Topic Questions

Value Returned
Method Call (blank if no Explanation
value)
The current number is initially the starting
plus3.currentNumber(); 2
number in the pattern.
The pattern adds 3 each time, so move to
plus3.next();
the next number in the pattern (5).
plus3.currentNumber(); 5 The current number is 5.
The pattern adds 3 each time, so move to
plus3.next();
the next number in the pattern (8).
The pattern adds 3 each time, so move to
plus3.next();
the next number in the pattern (11).
plus3.currentNumber(); 11 The current number is 11.
Move to the previous number in the pattern
plus3.prev();
(8).
Move to the previous number in the pattern
plus3.prev();
(5).
Move to the previous number in the pattern
plus3.prev();
(2).
plus3.currentNumber(); 2 The current number is 2.
There is no previous number in the pattern
plus3.prev();
prior to 2, so no action is taken.
plus3.currentNumber(); 2 The current number is 2.

Write the complete AdditonPattern class. Your implementation must meet all specifications and conform to
all examples.

AP Computer Science A Page 5 of 27


Test Booklet

Unit 5 Topic Questions

5. Consider the following class definition.

public class Element


{
public static int max_value = 0;
private int value;
public Element (int v)
{
value = v;
if (value > max_value)
{
max_value = value;
}
}
}

The following code segment appears in a class other than Element.

for (int i = 0; i < 5; i++)


{
int k = (int) (Math.random() * 10 + 1);
if (k >= Element.max_value)
{
Element e = new Element(k);
}
}

Which of the following best describes the behavior of the code segment?
(A) Exactly 5 Element objects are created.
(B) Exactly 10 Element objects are created.
Between 0 and 5 Element objects are created, and Element.max_value is increased only for the
(C)
first object created.
Between 1 and 5 Element objects are created, and Element.max_value is increased for every
(D)
object created.
Between 1 and 5 Element objects are created, and Element.max_value is increased for at least one
(E)
object created.

Page 6 of 27 AP Computer Science A


Test Booklet

Unit 5 Topic Questions

6. Consider the following class definition.

public class WordClass


{
private final String word;
private static String max_word = "";
public WordClass (String s)
{
word = s;
if (word.length() > max_word.length())
{
max_word = word;
}
}
}

Which of the following is a true statement about the behavior of WordClass objects?
(A) A WordClass object can change the value of the variable word more than once.
(B) Every time a WordClass object is created, the max_word variable is referenced.
(C) Every time a WordClass object is created, the value of the max_word variable changes.
(D) No two WordClass objects can have their word length equal to the length of max_word.
(E) The value of the max_word variable cannot be changed once it has been initialized.

7. Consider the following class definition.

public class RentalCar


{
private double dailyRate; // the fee per rental day
private double mileageRate; // the fee per mile driven
public RentalCar(double daily, double mileage)
{
dailyRate = daily;
mileageRate = mileage;
}
public double calculateFee(int days, int miles)
{
/* missing code */
}
}

The calculateFee method is intended to calculate the total fee for renting a car. The total fee is equal to the
number of days of the rental, days, times the daily rental rate plus the number of miles driven, miles, times
the per mile rate.

Which of the following code segments should replace /* missing code */ so that the calculateFee
method will work as intended?

AP Computer Science A Page 7 of 27


Test Booklet

Unit 5 Topic Questions

(A) return dailyRate + mileageRate;


(B) return (daily * dailyRate) + (mileage * mileageRate);
(C) return (daily * days) + (mileage * miles);
(D) return (days * dailyRate) + (miles * mileageRate);
(E) return (days + miles) * (dailyRate + mileageRate);

8. Consider the definition of the Person class below. The class uses the instance variable adult to indicate
whether a person is an adult or not.

public class Person

{
private String name;
private int age;
private boolean adult;
public Person (String n, int a)
{
name = n;
age = a;
if (age >= 18)
{
adult = true;
}
else
{
adult = false;
}
}
}

Which of the following statements will create a Person object that represents an adult person?
(A) Person p = new Person ("Homer", "adult");
(B) Person p = new Person ("Homer", 23);
(C) Person p = new Person ("Homer", "23");
(D) Person p = new Person ("Homer", true);
(E) Person p = new Person ("Homer", 17);

Page 8 of 27 AP Computer Science A


Test Booklet

Unit 5 Topic Questions

9. Consider the following class definition. Each object of the class Item will store the item’s name as itemName,
the item’s regular price, in dollars, as regPrice, and the discount that is applied to the regular price when the
item is on sale as discountPercent. For example, a discount of 15% is stored in discountPercent as
0.15.

public class Item


{
private String itemName;
private double regPrice;
private double discountPercent;
public Item (String name, double price, double discount)
{
itemName = name;
regPrice = price;
discountPercent = discount;
}
public Item (String name, double price)
{
itemName = name;
regPrice = price;
discountPercent = 0.25;
}
/* Other methods not shown */
}

Which of the following code segments, found in a class other than Item, can be used to create an item with a
regular price of $10 and a discount of 25% ?

I. Item b = new Item("blanket", 10.0, 0.25);


II. Item b = new Item("blanket", 10.0);
III. Item b = new Item("blanket", 0.25, 10.0);
(A) I only
(B) II only
(C) III only
(D) I and II only
(E) I, II, and III

AP Computer Science A Page 9 of 27


Test Booklet

Unit 5 Topic Questions

10. SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.

Assume that the classes listed in the Java Quick Reference have been imported where appropriate.
Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are
called only when their preconditions are satisfied.
In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined
in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will
not receive full credit.

The following class represents a customer. The variable name represents the name of the customer, and the variable
currAccNum represents the customer’s account number. Each time a Customer object is created, the static variable
nextAccNum is used to assign the customer’s account number.

public class Customer


{
private static int nextAccNum = 1;
private String name;
private int currAccNum;

public Customer(String n)
{
name = n;
currAccNum = nextAccNum;
nextAccNum++;
}
}

(a) Write a method for the Customer class that that will return a string representing a bill notice when passed a
double value representing an amount due.

For example, if the customer has name "Jeremiah", has account number 3, and has amount due 50.50, the method
should return a string in the following format.

Jeremiah, account number 3, please pay $50.50

Write the method below. Your implementation must conform to the example above.

(b) Write a method for the Customer class that returns the value of the next account number that will be assigned.

Write the method below.

(c) A student has written the following method to be included in the Customer class. The method is intended to
update the name of a customer but does not work as intended.

public void updateName(String name)

Page 10 of 27 AP Computer Science A


Test Booklet

Unit 5 Topic Questions

{
name = name;
}

Write a correct implementation of the updateName method that avoids the error in the student’s implementation.

Write the method below.

11. Consider the following class, which uses the instance variable balance to represent a bank account balance.

public class BankAccount


{
private double balance;
public double deposit(double amount)
{
/* missing code */
}
}

The deposit method is intended to increase the account balance by the deposit amount and then return the
updated balance. Which of the following code segments should replace /* missing code */ so that the
deposit method will work as intended?
amount = balance + amount;
(A) return amount;

balance = amount;
(B) return amount;
balance = amount;
(C) return balance;
balance = balance + amount;
(D) return amount;

balance = balance + amount;


(E) return balance;

AP Computer Science A Page 11 of 27


Test Booklet

Unit 5 Topic Questions

12. Consider the following class definition.

public class Password


{
private String password;
public Password (String pwd)
{
password = pwd;
}
public void reset(String new_pwd)
{
password = new_pwd;
}
}

Consider the following code segment, which appears in a method in a class other than Password. The code
segment does not compile.

Password p = new Password("password");


System.out.println("The new password is " + p.reset("password"));

Which of the following best identifies the reason the code segment does not compile?
(A) The code segment attempts to access the private variable password from outside the Password class.
(B) The new password cannot be the same as the old password.
(C) The Password class constructor is invoked incorrectly.
(D) The reset method cannot be called from outside the Password class.
(E) The reset method does not return a value that can be printed.

13. Consider the following class declaration.

public class Circle


{
private double radius;
public double computeArea()
{
private double pi = 3.14159;
public double area = pi * radius * radius;
return area;
}
// Constructor not shown.
}

Which of the following best explains why the computeArea method will cause a compilation error?

Page 12 of 27 AP Computer Science A


Test Booklet

Unit 5 Topic Questions

(A) Local variables declared inside a method cannot be declared as public or private.
(B) Local variables declared inside a method must all be private.
(C) Local variables declared inside a method must all be public.
(D) Local variables used inside a method must be declared at the end of the method.
(E) Local variables used inside a method must be declared before the method header.

14. Consider the following class definition.

public class Info


{
private String name;
private int number;
public Info(String n, int num)
{
name = n;
number = num;
}
public void changeName(String newName)
{
name = newName;
}
public int addNum(int n)
{
num += n;
return num;
}
}

Which of the following best explains why the class will not compile?
(A) The class is missing an accessor method.
(B) The instance variables name and number should be designated public instead of private.
(C) The return type for the Info constructor is missing.
(D) The variable name is not defined in the changeName method.
(E) The variable num is not defined in the addNum method.

AP Computer Science A Page 13 of 27


Test Booklet

Unit 5 Topic Questions

15. Consider the following class definition.

public class ItemInventory


{
private int numItems;
public ItemInventory(int num)
{
numItems = num;
}
public updateItems(int newNum)
{
numItems = newNum;
}
}

Which of the following best identifies the reason the class does not compile?
(A) The constructor header is missing a return type.
(B) The updateItems method is missing a return type.
(C) The constructor should not have a parameter.
(D) The updateItems method should not have a parameter.
(E) The instance variable numItems should be public instead of private.

16. Consider the following Bugs class, which is intended to simulate variations in a population of bugs. The
population is stored in the method’s int attribute. The getPopulation method is intended to allow methods
in other classes to access a Bugs object’s population value; however, it does not work as intended.

public class Bugs


{
private int population;

public Bugs(int p)
{
population = p;
}

public int getPopulation()


{
return p;
}
}

Which of the following best explains why the getPopulation method does NOT work as intended?

Page 14 of 27 AP Computer Science A


Test Booklet

Unit 5 Topic Questions

(A) The getPopulation method should be declared as private.


(B) The return type of the getPopulation method should be void.
(C) The getPopulation method should have at least one parameter.
(D) The variable population is not declared inside the getPopulation method.
(E) The instance variable population should be returned instead of p, which is local to the constructor.

17. Consider the following class definition.

public class FishTank


{
private double numGallons;
private boolean saltWater;
public FishTank(double gals, boolean sw)
{
numGallons = gals;
saltWater = sw;
}
public double getNumGallons()
{
return numGallons;
}
public boolean isSaltWater()
{
if (saltWater)
{
return "Salt Water";
}
else
{
return "Fresh Water";
}
}
}

Which of the following best explains the reason why the class will not compile?
(A) The variable numGallons is not declared in the getNumGallons method.
(B) The variable saltWater is not declared in the isSaltWater method.
(C) The isSaltWater method does not return the value of an instance variable.
(D) The value returned by the getNumGallons method is not compatible with the return type of the method.
(E) The value returned by the isSaltWater method is not compatible with the return type of the method.

AP Computer Science A Page 15 of 27


Test Booklet

Unit 5 Topic Questions

18. Consider the following class definition. The class does not compile.

public class Player


{
private double score;
public getScore()
{
return score;
}
// Constructor not shown
}

The accessor method getScore is intended to return the score of a Player object. Which of the following
best explains why the class does not compile?
(A) The getScore method should be declared as private.
(B) The getScore method requires a parameter.
(C) The return type of the getScore method needs to be defined as double.
(D) The return type of the getScore method needs to be defined as String.
(E) The return type of the getScore method needs to be defined as void.

19. Consider the following while loop. Assume that the int variable k has been properly declared and
initialized.

while (k < 0)
{
System.out.print("*");
k++;
}

Which of the following ranges of initial values for k will guarantee that at least one "*" character is printed?

I. k < 0
II. k = 0
III. k > 0
(A) I only
(B) III only
(C) I and II only
(D) II and III only
(E) I, II, and III

Page 16 of 27 AP Computer Science A


Test Booklet

Unit 5 Topic Questions

20. Consider the following class definitions.

public class Item


{
private int ID;
public Item (int id)
{
ID = id;
}
public int getID()
{
return ID;
}
public void addToCollection (ItemCollection c)
{
c.addItem(this);
}
}
public class ItemCollection
{
private int last_ID;
public void addItem(Item i)
{
if (i.getID() == last_ID)
{
System.out.print("ID " + i.getID() + " rejected; ");
}
else
{
last_ID = i.getID();
System.out.print("ID " + i.getID() + " accepted; ");
}
}
// Constructor not shown.
}

Consider the following code segment, which appears in a class other than Item or ItemCollection.

Item i = new Item(23);


Item j = new Item(32);
ItemCollection c = new ItemCollection();
i.addToCollection(c);
j.addToCollection(c);
j.addToCollection(c);
i.addToCollection(c);

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

AP Computer Science A Page 17 of 27


Test Booklet

Unit 5 Topic Questions

(A) ID 23 accepted; ID 32 accepted; ID 32 rejected; ID 23 accepted;


(B) ID 23 accepted; ID 32 accepted; ID 32 rejected; ID 23 rejected;
(C) ID 23 accepted; ID 32 rejected; ID 32 rejected; ID 23 accepted;
(D) ID 23 accepted; ID 32 rejected; ID 32 rejected; ID 23 rejected;
(E) ID 23 accepted; ID 32 rejected; ID 32 accepted; ID 23 rejected;

21. The following method is intended to return a string containing the character at position n in the string str. For
example, getChar("ABCDE", 2) should return "C".

/* missing precondition */
public String getChar(String str, int n)
{
return str.substring(n, n + 1);
}

Which of the following is the most appropriate precondition for the method so that it does not throw an exception?
(A) /* Precondition: 0 < n < str.length() - 1 */
(B) /* Precondition: 0 <= n <= str.length() - 1 */
(C) /* Precondition: 0 <= n <= str.length() */
(D) /* Precondition: n > str.length() */
(E) /* Precondition: n >= str.length() */

22. Consider the following method, which is intended to return the product of 3 and the nonnegative difference
between its two int parameters.

public int threeTimesDiff (int num1, int num2)


{
return 3 * (num1 - num2);
}

Which, if any, precondition is required so that the method works as intended for all values of the parameters that
satisfy the precondition?
(A) num1 > 0, num2 > 0
(B) num1 >= 0, num2 >= 0
(C) num1 >= num2
(D) num2 >= num1
(E) No precondition is required.

Page 18 of 27 AP Computer Science A


Test Booklet

Unit 5 Topic Questions

23. In the Toy class below, the raisePrice method is intended to increase the value of the instance variable
price by the value of the parameter surcharge. The method does not work as intended.

public class Toy


{
private String name;
private double price;
public Toy(String n, double p)
{
name = n;
price = p;
}
public void raisePrice(double surcharge) // Line 12
{
return price + surcharge; // Line 14
}

Which of the following changes should be made so that the class definition compiles without error and the method
raisePrice works as intended?
(A) Replace line 14 with surcharge += price;.
(B) Replace line 14 with price += surcharge;.
(C) Replace line 14 with return price += surcharge;.
(D) Replace line 12 with public raisePrice (double surcharge).
(E) Replace line 12 with public double raisePrice (double surcharge).

24. Consider the following class definition.

public class Something


{
private static int count = 0;
public Something()
{
count += 5;
}
public static void increment()
{
count++;
}
}

The following code segment appears in a method in a class other than Something.

Something s = new Something();


Something.increment();

Which of the following best describes the behavior of the code segment?

AP Computer Science A Page 19 of 27


Test Booklet

Unit 5 Topic Questions

The code segment does not compile because the increment method should be called on an object of the
(A)
class Something, not on the class itself.
The code segment creates a Something object s. The class Something’s static variable count is
(B)
initially 0, then increased by 1.
The code segment creates a Something object s. The class Something’s static variable count is
(C)
initially 0, then increased by 5, then increased by 1.
The code segment creates a Something object s. After executing the code segment, the object s has a
(D)
count value of 1.
The code segment creates a Something object s. After executing the code segment, the object s has a
(E)
count value of 5.

25. Consider the following class definition.

public class Tester


{
private int num1;
private int num2;
/* missing constructor */
}

The following statement appears in a method in a class other than Tester. It is intended to create a new
Tester object t with its attributes set to 10 and 20.

Tester t = new Tester(10, 20);

Which of the following can be used to replace /* missing constructor */ so that the object t is correctly
created?

Page 20 of 27 AP Computer Science A


Test Booklet

Unit 5 Topic Questions

public Tester(int first, int second)


{
(A) num1 = first;
num2 = second;
}
public Tester(int first, int second)
{
(B) num1 = 1;
num2 = 2;
}
public Tester(int first, int second)
{
(C) first = 1;
second = 2;
}
public Tester(int first, int second)
{
(D) first = 10;
second = 20;
}
public Tester(int first, int second)
{
(E) first = num1;
second = num2;
}

AP Computer Science A Page 21 of 27


Test Booklet

Unit 5 Topic Questions

26. Consider the following class definitions.

public class MenuItem


{
private double price;
public MenuItem(double p)
{
price = p;
}
public double getPrice()
{
return price;
}
public void makeItAMeal()
{
Combo meal = new Combo(this);
price = meal.getComboPrice();
}
}
public class Combo
{
private double comboPrice;
public Combo(MenuItem item)
{
comboPrice = item.getPrice() + 1.5;
}
public double getComboPrice()
{
return comboPrice;
}
}

The following code segment appears in a class other than MenuItem or Combo.

MenuItem one = new MenuItem(5.0);


one.makeItAMeal();
System.out.println(one.getPrice());

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


(A) 1.5
(B) 5.0
(C) 6.5
(D) 8.0
(E) Nothing is printed because the code will not compile.

Page 22 of 27 AP Computer Science A


Test Booklet

Unit 5 Topic Questions

27. Consider the following class definitions.

public class Class1


{
private int val1;
public Class1()
{
val1 = 1;
}
public void init ()
{
Class2 c2 = new Class2();
c2.init(this, val1);
}
public void update(int x)
{
val1 -= x;
}
public int getVal()
{
return val1;
}
}
public class Class2
{
private int val2;
public Class2()
{
val2 = 2;
}
public void init(Class1 c, int y)
{
c.update(val2 + y);
}
}

The following code segment appears in a method in a class other than Class1 or Class2.

Class1 c = new Class1();


c.init();
System.out.println(c.getVal());

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

AP Computer Science A Page 23 of 27


Test Booklet

Unit 5 Topic Questions

(A) 2
(B) 1
(C) 0
(D) -2
(E) Nothing is printed because the code segment does not compile.

Page 24 of 27 AP Computer Science A


Test Booklet

Unit 5 Topic Questions

28. Consider the BankAccount class below.

public class BankAccount


{
private final String ACCOUNT_NUMBER;
private double balance;
public BankAccount(String acctNumber, double beginningBalance)
{
ACCOUNT_NUMBER = acctNumber;
balance = beginningBalance;
}
public boolean withdraw(double withdrawAmount)
{
/* missing code */
}
}

The class contains the withdraw method, which is intended to update the instance variable balance under
certain conditions and return a value indicating whether the withdrawal was successful. If subtracting
withdrawAmount from balance would lead to a negative balance, balance is unchanged and the
withdrawal is considered unsuccessful. Otherwise, balance is decreased by withdrawAmount and the
withdrawal is considered successful.

Which of the following code segments can replace /* missing code */ to ensure that the withdraw method
works as intended?

I.
if (withdrawAmount > balance)
{
return "Overdraft";
}
else
{
balance -= withdrawAmount;
return true;
}

II.
if (withdrawAmount > balance)
{
return false;
}
else
{
balance -= withdrawAmount;
return balance;
}

AP Computer Science A Page 25 of 27


Test Booklet

Unit 5 Topic Questions

III.
if (withdrawAmount > balance)
{
return false;
}
else
{
balance -= withdrawAmount;
return true;
}
(A) I only
(B) II only
(C) III only
(D) I and II only
(E) I, II, and III

Page 26 of 27 AP Computer Science A


Test Booklet

Unit 5 Topic Questions

29. The class Worker is defined below. The class includes the method getEarnings, which is intended to return
the total amount earned by the worker.

public class Worker


{
private double hourlyRate;
private double hoursWorked;
private double earnings;
public Worker(double rate, double hours)
{
hourlyRate = rate;
hoursWorked = hours;
}
private void calculateEarnings()
{
double earnings = 0.0;
earnings += hourlyRate * hoursWorked;
}
public double getEarnings()
{
calculateEarnings();
return earnings;
}
}

The following code segment appears in a method in a class other than Worker. The code segment is intended to
print the value 800.0, but instead prints a different value because of an error in the Worker class.

Worker bob = new Worker(20.0, 40.0);


System.out.println(bob.getEarnings());

Which of the following best explains why an incorrect value is printed?


(A) The private variables hourlyRate and hoursWorked are not properly initialized.
(B) The private variables hourlyRate and hoursWorked should have been declared public.
(C) The private method calculateEarnings should have been declared public.
(D) The variable earnings in the calculateEarnings method is a local variable.
The variables hourlyRate and hoursWorked in the calculateEarnings method are local
(E)
variables.

AP Computer Science A Page 27 of 27

You might also like