Comp Sci Test Unit 5

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

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

A. I only If k is less than 0, the loop condition k < 0 will evaluate to true and the body of the loop is guaranteed to execute at least once. If k is greater than or equal to 0, the loop condition will evaluate to false and the body of the loop will never execute.

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; Correct. First, i is accepted and last_ID is set to 23; then j is accepted and last_ID is set to 32; then j is rejected, since last_ID is already equal to 32; finally, i is accepted, since its ID is not equal to last_ID.

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. Correct. Local variables in the body of a method cannot be declared as public or private.

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; } The code segment sets the values of the instance variables num1 and num2 to the values of the parameters first and second, respectively. When the object t is constructed, the constructor is passed the values 10 and 20, which are assigned to the instance variables.

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 / For the call to substring to work without error, n must be between 0 and str.length() - 1, inclusive. Otherwise, an IndexOutOfBoundsException will occur.

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. Correct. The static variable max_word is shared among all WordClass objects. Every time the WordClass constructor is invoked, the length of the max_word variable is compared to the length of the word passed as a parameter to the constructor.

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); The Person class constructor requires a String parameter and an int parameter; the person will correctly be designated as an adult because the age parameter is greater than 18.

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;. Correct. The raisePrice method is intended to increase the value of price by adding surcharge to it; the statement "price += surcharge" works as intended. The method should not return a value, as it is a void mutator method, not an accessor method.

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. Correct. The mutator method updateItems must have a return type. In this case, since no value is returned, the return type should be void.

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 Correct. The code segment creates a new MenuItem with price set to 5.0. The makeItAMeal method uses the this keyword to pass the current object to the Combo constructor, creating a new Combo with comboPrice set to 6.5. The makeItAMeal method then calls the getComboPrice method and assigns the returned value 6.5 to price. The call to getPrice returns the value of price, or 6.5.

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

C. III only Correct. Code segment I returns a String value when withdrawal is unsuccessful; it will not compile because the return type for the withdraw method is boolean. Code segment II returns a double value (the new balance) when withdrawal is successful; it will not compile because the return type for the withdraw method is boolean. Code segment III returns an appropriate boolean value for each execution path in accordance with the method description.

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. Correct. The class Something's static variable count is initially 0. The first line of the code segment creates a new Something object s and increases count by 5. The second line of the code segment increases count 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. Correct. The accessor method getScore is intended to return the value of the double instance variable score, so it should be defined as type double.

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 expression num1 - num2 represents the nonnegative difference between num1 and num2 only when num1 >= num2.

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) { / implementation not shown / } The constructor should be designated as public so that Car objects can be created outside the class. The instance variables make and model should be designated as private so they are kept internal to the class.

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 instance variables day, month, and year should be designated as private so they are kept internal to the class. The constructor should be designated as public so that Date objects can be created outside the class. The setDate method should be designated as public, as it is intended to be accessed from outside the class.

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 / } The instance variables score and id should be designated as private so they are kept internal to the class. The constructor should be designated as public so that Player objects can be created outside the class. The getScore method should be designated as public, as it is intended to be accessible from outside the class.

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 Correct. When c is first created, its private variable val1 is assigned 1. When c's init method is called, the keyword this is used to pass the current object c along with its val1 value to the init method of c2. That method calls c's update method with the parameter 3, and c's update method sets val1 to 1 - 3, or -2.

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 only

D. I and II only Code segment I uses the three-parameter constructor to create an Item object with the regular price of $10 and the discount of 0.25, or 25%. Code segment II uses the two-parameter constructor to create an Item object with the regular price of $10 and the default discount of 0.25, or 25%. Code segment III incorrectly creates an Item object with a regular price of $0.25 and a default discount of 10.0, or 1,000%.

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. Correct. The local variable earnings declared in the calculateEarnings method has the same name as the private variable earnings. The local variable is assigned the intended amount, but the private variable is never updated. The private variable is the one printed by the getEarnings method.

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); Correct. The daily rental rate is stored in the instance variable dailyRate. The per mile rate is stored in the instance variable mileageRate. Therefore, the total rental fee will be equal to (days * dailyRate) + (miles * mileageRate), which is returned.

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. Correct. Inside the for loop, k is assigned a random integer value from 1 to 10 inclusive. Since Element.max_value is initialized to 0 by default, the condition k >= Element.max_value is guaranteed to evaluate to true during the first iteration of the loop. Therefore, an Element object will be created and the value of Element.max_value will increase from 0 to k. We are not guaranteed that more Element objects will be created, as it could happen that the 4 subsequent values of k are smaller than the first one.

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. The getPopulation method should return the value of the instance variable population. The variable p is not defined in the getPopulation method and trying to access it will cause a compile-time error.

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. Correct. The reset method has return type void, so it does not return a value.

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. The return type of the isSaltWater method is declared as boolean; however, the method is returning a String value. These two data types are not compatible.

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.

E. The variable num is not defined in the addNum method. Correct. Although the variable num is used in the Info constructor, it is passed to the constructor as a parameter. Therefore, it is only defined in the constructor. If another method like addNum wants to use a variable of the same name, it is allowed to do so, but the variable must be declared inside that method or passed to it as a parameter. Otherwise, a compile-time error will occur.

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; Correct. The instance variable balance is updated correctly by adding amount to the current value of balance. Once the update is made, the value of balance is returned.


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

MCC Horngren's Accounting 1090 Chapter 8

View Set

Neuroscience, Sensation and Perception

View Set

System Analysis and Design Chapter 10

View Set

Hospitality Management Chapter 6 through 14

View Set

CompTIA A+ Cert Master 3.1 Hardware Study

View Set