AP Computer Science Unit 5 Test

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

You can add behavior to an object by adding_____ to the class

methods

To make objects easily printable, write a ____ method that returns a text representation

toString

T/F A class can have a filed that is a array

true

T/F A class may contain multiple constructors

true

T/F Constructors may call other constructors("chaining")

true

T/F Getters and Setters are instance methods

true

T/F You can access fields inside a class's methods

true

How do you access private fields from client code

use getters/setters

What is an instance method

A method that can be called using an object

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

A) Local variables declared inside a method cannot be declared as public or private

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() */

B) /* Precondition: 0 <= n <= str.length() - 1 */

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.

B) Every time a WordClass object is created, the max_word variable is referenced

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);

B) Person p = new Person ("Homer", 23);

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.

C) 6.5

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? A) The code segment does not compile because the increment method should be called on an object of the class Something, not on the class itself. B) The code segment creates a Something object s. The class Something's static variable count is initially 0, then increased by 1. C) The code segment creates a Something object s. The class Something's static variable count is initially 0, then increased by 5, then increased by 1. D) The code segment creates a Something object s. After executing the code segment, the object s has a count value of 1. E) The code segment creates a Something object s. After executing the code segment, the object s has a count value of 5.

C) The code segment creates a Something object s. The class Something's static variable count is initially 0, then increased by 5, then increased by 1.

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.

C) The return type of the getScore method needs to be defined as double.

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? A) 2 B) 1 C) 0 D) -2 E) Nothing is printed because the code segment does not compile.

D) -2

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. C) Between 0 and 5 Element objects are created, and Element.max_value is increased only for the first object created. D) Between 1 and 5 Element objects are created, and Element.max_value is increased for every object created. E) Between 1 and 5 Element objects are created, and Element.max_value is increased for at least one object created.

E) Between 1 and 5 Element objects are created, and Element.max_value is increased for at least one object created.

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.

E) The variable num is not defined in the addNum method.

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

I only

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 */ } } . 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; } III. if (withdrawAmount > balance) { return false; } else { balance -= withdrawAmount; return true; }

III only

What what is true about code p1 and p2 with the same points

It creates two Point objects with identical data

What is the correct way to create a Name object

Name n = new Name("Will", "c", "Smith");

What is the correct way to create a Point object

Point p = new Point(2,3);

T/F A class is a blueprint for a type of Java object

True

T/F A java object has data and behavior

True

A class's ____ creates a new object that may contain initial values for the fields

constructor

A BankAccount object (acct) has a computeInterest method. What is the correct way to call it

double result = acct.computeInterest(42);

T/F A class is an instance of an object. One object can be used to create many classes

false

T/F private fields can be directly changed from the client code

false

What is the term for having multiple constructors with different parameters

overloading

A Pokémon object (p1) has a damage method. What is the correct way to call the damage method

p1.damage();

Fields can be protected from external modification by making them ____

private

What is the correct syntax for a constructor for the Book class

public Book(String title, String author){

What is the correct method header for the toString method

public String toString() {

Methods that change an objects fields are called

setters/mutators

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? 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;

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

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? A) public Tester(int first, int second) { num1 = first; num2 = second; } B) public Tester(int first, int second) { num1 = 1; num2 = 2; } C) public Tester(int first, int second) { first = 1; second = 2; } D) public Tester(int first, int second) { first = 10; second = 20; } E) public Tester(int first, int second) { first = num1; second = num2; }

A) public Tester(int first, int second) { num1 = first; num2 = second; }

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

B) Replace line 14 with price += surcharge;.

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.

C) num1 >= num2

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. E) The variables hourlyRate and hoursWorked in the calculateEarnings method are local variables.

D) The variable earnings in the calculateEarnings method is a local variable

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? 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);

D) return (days * dailyRate) + (miles * mileageRate);

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

E) The instance variable population should be returned instead of p, which is local to the constructor.

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.

B) The updateItems method is missing a return type.

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? A) public String make; public String model; public Car(String myMake, String myModel) { /* implementation not shown */ } B) public String make; public String model; private Car(String myMake, String myModel) { /* implementation not shown */ } C) private String make; private String model; public Car(String myMake, String myModel) { /* implementation not shown */ } D) public String make; private String model; private Car(String myMake, String myModel) ( /* implementation not shown */ } E) private String make; private String model; private Car(String myMake, String myModel) { /* implementation not shown */ }

C) private String make; private String model; public Car(String myMake, String myModel)

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? A) private int day; private int month; private int year; private Date() { /* implementation not shown */ } private void setDate(int d, int m, int y) { /* implementation not shown */ } B) private int day; private int month; private int year; public Date() { /* implementation not shown */ } private void setDate(int d, int m, int y) { /* implementation not shown */ } C) private int day; private int month; private int year; public Date() { /* implementation not shown */ } public void setDate(int d, int m, int y) { /* implementation not shown */ } D) public int day; public int month; public int year; private Date() { /* implementation not shown */ } private void setDate(int d, int m, int y) { /* implementation not shown */ } E) public int day; public int month; public int year; public Date() { /* implementation not shown */ } public void setDate(int d, int m, int y) { /* implementation not shown */ }

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

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? A) private int score; private int id; private Player(int playerScore, int playerID) { /* implementation not shown */ } private int getScore() { /* implementation not shown */ } B) private int score; private int id; public Player(int playerScore, int playerID) { /* implementation not shown */ } private int getScore() { /* implementation not shown */ } C) private int score; private int id; public Player(int playerScore, int playerID) { /* implementation not shown */ } public int getScore() { /* implementation not shown */ } D) public int score; public int id; public Player(int playerScore, int playerID) { /* implementation not shown */ } private int getScore() { /* implementation not shown */ } E) public int score; public int id; public Player(int playerScore, int playerID) { /* implementation not shown */ } public int getScore() { /* implementation not shown */ }

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

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% ? Item b = new Item("blanket", 10.0, 0.25); Item b = new Item("blanket", 10.0); Item b = new Item("blanket", 0.25, 10.0);

D) I and II only

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.

E) The reset method does not return a value that can be printed.

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.

E) The value returned by the isSaltWater method is not compatible with the return type of the method.

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? A) amount = balance + amount; return amount; B) balance = amount; return amount; C) balance = amount; return balance; D) balance = balance + amount; return amount; E) balance = balance + amount; return balance;

E) balance = balance + amount; return balance;


संबंधित स्टडी सेट्स

Chapter 10 - Access Control Methods and Models

View Set

MGMT 329 CH 6 RECRUITING 6.1-6.7

View Set

Organizational Behavior - Exam 1

View Set

Chapter 15 Pre-Lecture Questions

View Set

Preguntas de la semana 2.2 Spanish 1

View Set

Russian 225 Подготовка к контрольной работе (Урок 6)

View Set

OB Chapt 11 Maternal Adaptation During Pregnancy

View Set