APCSA EMPA MCQ REVIEW

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Consider the following code segment. int num = 1; int count = 0; while (num <= 10) { if (num % 2 == 0 && num % 3 == 0) { count++; } num++; } What value is stored in the variable count as a result of executing the code segment?

A. 1

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

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;

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.

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

Consider the following method. public static String changeStr(String str) { String result = ""; for (int i = str.length() - 1; i >= str.length() / 2; i -= 2) { result += str.substring(i, i + 1); } return result; } What value is returned as a result of the method call changeStr("12345") ?

B. "53"

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?

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

Consider the following code segment. int num = 1; while (num < 5) { System.out.print("A"); num += 2; } What is printed as a result of executing the code segment?

B. AA

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?

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?

B. Person p = new Person ("Homer", 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?

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

Consider the following code segment. for (int j = 0; j < 3; j++) { for (int k = 0; k < 4; k++) { System.out.println("Fun"); } } Which of the following best explains how changing the outer for loop header to for (int j = 0; j <= 3; j++) affects the output of the code segment?

B. The string "Fun" will be printed more times because the outer loop will execute more times.

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?

B. The updateItems method is missing a return type.

Consider the following code segment. int j = 1; while (j < 5) { int k = 1; while (k < 5) { System.out.println(k); k++; } j++; } Which of the following best explains the effect, if any, of changing the first line of code to int j = 0; ?

B. There will be four more values printed because the outer loop will iterate one additional time.

Consider the following code segment. for (int j = 1; j < 10; j += 2) { System.out.print(j); } Which of the following code segments will produce the same output as the code segment above?

B. int j = 1; while (j < 10) { System.out.print(j); j += 2; }

Consider the following code segment. int k = 0; /* missing loop header */ { k++; System.out.print(k + " "); } Which of the following can be used as a replacement for /* missing loop header */ so that the code segment prints out the string "1 2 3 4 "?

B. while (k < 4)

Consider the following code segment. for (int x = 0; x <= 4; x++) // Line 1 { for (int y = 0; y < 4; y++) // Line 3 { System.out.print("a"); } System.out.println(); } Which of the following best explains the effect of simultaneously changing x <= 4 to x < 4 in line 1 and y < 4 to y <= 4 in line 3 ?

C. "a" will be printed the same number of times because while the number of output lines will decrease by 1, the length of each line will increase by 1.

int counter = 0; for (int x = 10; x > 0; x--) { for (int y = x; y <= x; y++) { counter++; // line 6 } } How many times will the statement in line 6 be executed as a result of running the code segment?

C. 10

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?

C. 6.5

Consider the following code segments. Code segment 2 is a revision of code segment 1 in which the loop increment has been changed. Code Segment 1 int sum = 0; for (int k = 1; k <= 30; k++) { sum += k; } System.out.println("The sum is: " + sum); Code Segment 2 int sum = 0; for (int k = 1; k <= 30; k = k + 2) { sum += k; } System.out.println("The sum is: " + sum); Code segment 1 prints the sum of the integers from 1 through 30, inclusive. Which of the following best explains how the output changes from code segment 1 to code segment 2 ?

C. Code segment 2 will print the sum of only the odd integers from 1 through 30, inclusive because it starts k at one, increments k by twos, and terminates when k exceeds 30.

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

C. III only

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?

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 method definition. The method printAllCharacters is intended to print out every character in str, starting with the character at index 0. public static void printAllCharacters(String str) { for (int x = 0; x < str.length(); x++) // Line 3 { System.out.print(str.substring(x, x + 1)); } } The following statement is found in the same class as the printAllCharacters method. printAllCharacters("ABCDEFG"); Which choice best describes the difference, if any, in the behavior of this statement that will result from changing x < str.length() to x <= str.length() in line 3 of the method?

C. The method call, which worked correctly before the change, will now cause a run-time error because it attempts to access a character at index 7 in a string whose last element is at index 6.

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?

C. The return type of the getScore method needs to be defined as 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?

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

C. private String make; private String model; public Car(String myMake, String myModel) { /* implementation not shown */ }

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?

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?

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

D. -2

Consider the following code segment. int count = 5; while (count < 100) { count = count * 2; } count = count + 1; What will be the value of count as a result of executing the code segment?

D. 161

Consider the following code segment. String str = "a black cat sat on a table"; int counter = 0; for (int i = 0; i < str.length() - 1; i++) { if (str.substring(i, i + 1).equals("a") && !str.substring(i + 1, i + 2).equals("b")) { counter++; } } System.out.println(counter); What is printed as a result of executing this code segment?

D. 5

Consider the following code segment. int outerMax = 10; int innerMax = 5; for (int outer = 0; outer < outerMax; outer++) { for (int inner = 0; inner <= innerMax; inner++) { System.out.println(outer + inner); } } How many values will be printed when the code segment is executed?

D. 60

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

D. I and II only

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?

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

Consider the following code segment. int count = 0; for (int k = 0; k < 10; k++) { count++; } System.out.println(count); Which of the following code segments will produce the same output as the code segment above?

D. int count = 0; for (int k = 9; k >= 0; k--) { count++; } System.out.println(count);

Consider the following code segment. for (int outer = 0; outer < 3; outer++) { for (/* missing loop header */) { System.out.print(outer + "" + inner + "_"); } } Which of the following can be used as a replacement for /* missing loop header */ so that the code segment produces the output 00_01_02_11_12_22_ ?

D. int inner = outer; inner < 3; inner++

The following method is intended to print the number of digits in the parameter num. public int numDigits(int num) { int count = 0; while (/* missing condition */) { count++; num = num / 10; } return count; } Which of the following can be used to replace /* missing condition */ so that the method will work as intended?

D. num != 0

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?

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

Consider the following code segment, which is intended to print the sum of all the odd integers from 0 up to and including 101. int r = 0; int sum = 0; /* missing loop header */ { if (r % 2 == 1) { sum += r; } r++; } System.out.println(sum); Which of the following could replace /* missing loop header */ to ensure that the code segment will work as intended?

D. while (r <= 101)

Consider the following code segment. int val = 1; while (val <= 6) { for (int k = 0; k <= 2; k++) { System.out.println("Surprise!"); } val++; } How many times is the string "Surprise!" printed as a result of executing the code segment?

E. 18

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?

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

Consider the following code segment. /* missing loop header */ { for (int k = 0; k < 4; k++) { System.out.print(k); } System.out.println(); } The code segment is intended to produce the following output. 0123 0123 0123 Which of the following can be used to replace /* missing loop header */ so that the code segment works as intended? I. for (int j = 0; j < 3; j++) II. for (int j = 1; j < 3; j++) III. for (int j = 1; j <= 3; j++)

E. I and III

Consider the following two code segments. Code segment II is a revision of code segment I in which the loop header has been changed. I. for (int k = 1; k <= 5; k++) { System.out.print(k); } II. for (int k = 5; k >= 1; k--) { System.out.print(k); } Which of the following best explains how the output changes from code segment I to code segment II?

E. The code segments print the same values but in a different order, because code segment I iterates from 1 to 5 and code segment II iterates from 5 to 1.

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?

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

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?

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?

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

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?

E. The variable num is not defined in the addNum 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?

E. balance = balance + amount; return balance;

Consider the following method. public String wordPlay(String word) { String str = ""; for (int k = 0; k < word.length(); k++) { if (k % 3 == 0) { str = word.substring(k, k + 1) + str; } } return str; } The following code segment appears in another method in the same class as wordPlay. System.out.println(wordPlay("Computer Science")); What is printed as a result of executing the code segment?

E. eeSepC

Consider the following code segment. for (int k = 1; k <= 7; k += 2) { System.out.print(k); } Which of the following code segments will produce the same output as the code segment above?

E. for (int k = 1; k <= 8; k += 2) { System.out.print(k); }

Consider the following code segment. int count = 0; for (int x = 1; x <= 3; x++) { /* missing loop header */ { count++; } } System.out.println(count); Which of the following should be used to replace /* missing loop header */ so that the code segment will print 6 as the value of count ?

E. for (int y = 0; y < x; y++)


Kaugnay na mga set ng pag-aaral

Catarata (GPC: Sin comorbilidades de segmento anterior / Adulto y adulto mayor en primer nivel)

View Set

Ap Gov Chapter 13 Practice Test--- Ari Cerja

View Set

Chapter 19: Documenting and Reporting

View Set

Preparation of Closing Statements UNIT EXAM PT.2

View Set

drivers training ch 9 true and false

View Set

ABM 1041 Applied Microeconomics Final Study Guide, ABM 1041 Applied Microeconomics Exam 1 Study Guide

View Set

Advanced Auditing Chapter 3, Section E, Module A MC, Section B, Section D, Module A Other Public Accounting Services, Chapter 2: Professional Standards, Section C, MOdule C - Legal Liability, Module B - Professional Ethics, Advanced Auditing Ch 1

View Set