AP Computer Science midterm study guide

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

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?

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?

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

Consider the following code segment. int x = 10; int y = 20; /* missing code */ System.out.print(top / bottom); Which of the following replacements for /* missing code */ will cause an ArithmeticException to occur? (I) int top = x - y; int bottom = y - x; (II) int top = 2 * x; int bottom = y - top; (III)int top = x + y; int bottom = 2 * top;

II only

Consider the following code segment. int x = 4; int y = 6; x -= y; y += x; Which of the following best describes the behavior of the code segment?

Both the value of x and the value of y have been decreased.

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?

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

Consider the following code segment. for (int i = 0; i < 5; i++) // Line 1 { for (int j = 0; j < 5; j++) { int k = i + j; System.out.print(k + " "); } } Which of the following best describes the result of changing i < 5 to i > 5 in line 1?

Nothing will be printed because the body of the outer for loop will not execute at all.

Consider the following code segment. double d = 0.25; int i = 3; double diff = d - i; System.out.print((int)diff - 0.5); What is printed as a result of executing the code segment?

-2.5

Consider the following code segment. int j = 10; int k = 8; j += 2; k += j; System.out.print(j); System.out.print(" "); System.out.println(k); What is printed when the code segment is executed?

12 20

Consider the following code segment. int a = 100; while (a > 1) { System.out.println("$"); a /= 2; } How many $'s are printed as a result of executing the code segment?

6

Consider the following class definition. public class Email { private String username; public Email(String u) { username = u; } public void printThis() { System.out.println(this); } public String toString() { return username + "@example.com"; } } The following code segment appears in a method in another class. Email e = new Email("default"); e.printThis(); What, if anything, is printed as a result of executing the code segment

[email protected]

Consider the following incomplete code segment, which is intended to print the sum of the digits in num. For example, when num is 12345, the code segment should print 15, which represents the sum 1 + 2 + 3 + 4 + 5. int num = 12345; int sum = 0; /* missing loop header */ { sum += num % 10; num /= 10; } System.out.println(sum); Which of the following should replace /* missing loop header */ so that the code segment will work as intended?

while (num > 0)

Consider the following class definition. public class Contact { private String contactName; private String contactNumber; public Contact(String name, String number) { contactName = name; contactNumber = number; } public void doSomething() { System.out.println(this); } public String toString() { return contactName + " " + contactNumber; } } The following code segment appears in another class. Contact c = new Contact("Alice", "555-1234"); c.doSomething(); c = new Contact("Daryl", ""); c.doSomething(); What is printed as a result of executing the code segment?

Alice 555-1234 Daryl

Consider the following code segment. double p = 10.6; double n = -0.2; System.out.println((int) (p + 0.5)); System.out.print((int) (n - 0.5)); What is printed as a result of executing the code segment?

11 0

Consider the following method. public static int mystery(String string1, String string2) { String temp = string1; int position = 0; int result = 0; while(temp.indexOf(string2) >= 0) { position = temp.indexOf(string2); result++; temp = temp.substring(position + 1); } return result; } The following code segment appears in another method in the same class. System.out.println(mystery("Mississippi", "si")); What, if anything, is printed as a result of executing the code segment?

2

Consider the code segment below. int x = 10; int y = 20; System.out.print(y + x / y); What is printed as a result of executing the code segment?

20

Consider the following code segment. double a = 7; int b = (int) (a / 2); double c = (double) b / 2; System.out.print(b); System.out.print(" "); System.out.print(c); What is printed as a result of executing the code segment?

3 1.5

In the code segment below, the int variable temp represents a temperature in degrees Fahrenheit. The code segment is intended to print a string based on the value of temp. The following table shows the string that should be printed for different temperature ranges. Temperature Range String to Print 31 and below = "cold" 32-50 = "cool" 51-70 = "moderate"​ 71 and above = "warm" String weather; if (temp <= 31) { weather = "cold"; } else { weather = "cool"; } if (temp >= 51) { weather = "moderate"; } else { weather = "warm"; } System.out.print(weather); Which of the following test cases can be used to show that the code does NOT work as intended? (I) temp = 30 (II) temp = 51 (III) temp = 60

I only

Consider the following code segment. System.out.print("cat "); System.out.println("dog "); System.out.println("horse "); System.out.print("cow "); What is printed as a result of executing the code segment?

cat dog horse cow

Consider the following code segment. for (int k = 0; k < 4; k++) { /* missing loop header */ { System.out.print(k); } System.out.println(); } The code segment is intended to produce the following output. 0 11 222 3333 Which of the following can be used to replace /* missing loop header */ so that the code segment will work as intended?

for (int h = k; h >= 0; h--)

Consider the following code segment. int total = 0; for (int k = 0; k <= 100; k += 2) { total += k; } Which of the following for loops could be used to replace the for loop in the original code segment so that the original and the revised code segments store the same value in total?

for (int k = 1; k <= 101; k += 2) { total += k - 1; }

Consider the following code segment in which the int variables a and b have been properly declared and initialized. if (a < b) { a++; } else if (b < a) { b++; } else { a++; b++; } Which of the following code segments is equivalent to the code segment above?

if (a == b) { a++; b++; } else if (a < b) { a++; } else { b++; }

Consider the following code segment. int a = 1; int b = 2; int c = 3; int d = 4; double x = a + b * c % d; What is the value of x when the code segment has been executed?

3.0

Consider the following code segment. int quant = 20; int unitPrice = 4; int ship = 8; int total; if (quant > 10) { unitPrice = 3; } if (quant > 20) { ship = 0; } total = quant * unitPrice + ship; What is the value of total after this code segment has been executed?

68

Consider the following definition of the class Student. public class Student { private int grade_level; private String name; private double GPA; public Student (int lvl, String nm, double gr) { grade_level = lvl; name = nm; GPA = gr; } } Which of the following object initializations will compile without error?

Student max = new Student (10, "Max", 3.75);

A store sells rope only in whole-foot increments. Given three lengths of rope, in feet, the following code segment is intended to display the minimum length of rope, in feet, that must be purchased so that the rope is long enough to be cut into the three lengths. For example, for lengths of 2.8 feet, 3 feet, and 5 feet, the minimum length of rope that must be purchased is 11 feet. For these inputs, the code segment should display 11. As another example, for lengths of 1.1 feet, 3.2 feet, and 2 feet, the minimum length of rope that must be purchased is 7 feet. For these inputs, the code segment should display 7. double len1; double len2; double len3; double total = len1 + len2 + len3; int minLength = (int) (total + 0.5); System.out.print(minLength); Which of the following best describes the behavior of the code segment?

The code segment works as intended but only when the sum of the three lengths is an integer or the decimal part of the sum of the three lengths is greater than or equal to 0.5.

Consider the following variable declarations and initializations. int a = 2; int b = 6; int c = 3; Which of the following expressions evaluates to false ?

a < b != c < b

The Fraction class below will contain two int attributes for the numerator and denominator of a fraction. The class will also contain a method fractionToDecimal that can be accessed from outside the class. public class Fraction { /* missing code */ // constructor and other methods not shown } Which of the following replacements for /* missing code */ is the most appropriate implementation of the class?

private int numerator; private int denominator; public double fractionToDecimal() { return (double) numerator / denominator; }

Consider the following class definition. public class Person { private String name; /* missing constructor */ } The statement below, which is located in a method in a different class, creates a new Person object with its attribute name initialized to "Washington". Person p = new Person("Washington"); Which of the following can be used to replace /* missing constructor */ so that the object p is correctly created?

public Person(String n) { name = n; }

Consider the following code segment. boolean a = true; boolean b = false; System.out.print((a == !b) != false); What is printed as a result of executing this code segment?

true

Consider the following expression. (3 + 4 == 5) != (3 + 4 >= 5) What value, if any, does the expression evaluate to?

true

Consider the following code segment. int a = 1; String result = ""; while (a < 20) { result += a; a += 5; } System.out.println(result); What, if anything, is printed as a result of executing the code segment?

161116

Consider the following code segment. int j = 1; while (j <= 5) { for (int k = 4; k > 1; k--) { System.out.println("ha"); // line 6 } j++; } How many times will the print statement on line 6 execute?

15

Consider the following method. /* missing precondition */ public void someMethod(int j, int k, String oldString) { String newString = oldString.substring(j, k); System.out.println("New string: " + newString); } Which of the following is the most appropriate precondition for someMethod so that the call to substring does not throw an exception?

/* Precondition: 0 <= j <= k <= oldString.length() */

The method addItUp(m, n) is intended to print the sum of the integers greater than or equal to m and less than or equal to n. For example, addItUp(2, 5) should return the value of 2 + 3 + 4 + 5. /* missing precondition */ public static int addItUp(int m, int n) { int sum = 0; for (int j = m; j <= n; j++) { sum += j; } return sum; } Which of the following is the most appropriate precondition for the method?

/* Precondition: m <= n */

Consider the following code segment. int m = 8; int n = 3; if (m + n > 10) { System.out.print(m + n); } if (m - n > 0) { System.out.print(m - n); } What, if anything, is printed as a result of executing the code segment?

115

Consider the following code segment. int x = /* initial value not shown */; int y = /* initial value not shown */; int z = x; z /= y; z += 2; Which of the following best describes the behavior of the code segment?

It sets z to (x / y) + 2.

Consider the following class definition. The method appendIt is intended to take the string passed as a parameter and append it to the instance variable str. For example, if str contains "week", the call appendIt("end") should set str to "weekend". The method does not work as intended. public Class StringThing { private String str; public StringThing(String myStr) { str = myStr; } public void appendIt(String s) // line 10 { str + s; // line 12 } } Which of the following changes should be made so that the appendIt method works as intended?

Line 12 should be changed to str = str + s;.

Consider the following code segments, which differ only in their loop header. Code Segment I for (int i = 0; i < 10; i++) { System.out.print( "*" ); } Code Segment II for (int i = 1; i <= 10; i++) { System.out.print( "*" ); } Which of the following best explains how the difference in the two loop headers affects the output?

The output of the code segments is the same because the loops in both code segments iterate 10 times.

Consider the following method. public String mystery(String word, int num) { String result = ""; for (int k = num; k >= 0; k--) { result += word.substring(0, k); } return result; } What is returned as a result of the call mystery("computer", 3) ?

comcoc

Consider the following code segment. System.out.println("W"); System.out.println("X"); System.out.print("Y"); System.out.print("Z"); What is printed as a result of executing the code segment?

W X YZ

Which statement correctly declares a variable that can store a temperature rounded to the nearest tenth of a degree?

double patientTemp;

Consider the following code segment, which is intended to display 0.5. int num1 = 5; int num2 = 10; double ans = num1 / num2; System.out.print(ans); Which of the following best describes the error, if any, in the code segment?

The code should have cast either num1 or num2 in the expression num1 / num2 to double.

Consider the following code segment. int k = 35; while (k >= 0) { System.out.println("X"); k -= 5; } How many times will the string "X" be printed as a result of executing the code segment?

8

Consider the following class definition. Each object of the class Employee will store the employee's name as name, the number of weekly hours worked as wk_hours, and hourly rate of pay as pay_rate. public class Employee { private String name; private int wk_hours; private double pay_rate; public Employee(String nm, int hrs, double rt) { name = nm; wk_hours = hrs; pay_rate = rt; } public Employee(String nm, double rt) { name = nm; wk_hours = 20; pay_rate = rt; } } Which of the following code segments, found in a class other than Employee, could be used to correctly create an Employee object representing an employee who worked for 20 hours at a rate of $18.50 per hour? (I.) Employee e1 = new Employee("Lili", 20, 18.5); (II.) Employee e2 = new Employee("Steve", 18.5); (III.) Employee e3 = new Employee("Carol", 20);

I and II only

Consider the following class definition. public class BoolTest { private int one; public BoolTest(int newOne) { one = newOne; } public int getOne() { return one; } public boolean isGreater(BoolTest other) { /* missing code */ } } The isGreater method is intended to return true if the value of one for this BoolTest object is greater than the value of one for the BoolTest parameter other, and false otherwise. The following code segments have been proposed to replace /* missing code */. (I) return one > other.one; (II) return one > other.getOne(); (III) return getOne() > other.one; Which of the following replacements for /* missing code */ can be used so that isGreater will work as intended?

I, II and III

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

III only

Consider the following class definition, which represents two scores using the instance variables score1 and score2. The method reset is intended to set to 0 any score that is less than threshold. The method does not work as intended. public class TestClass { private int score1; private int score2; public TestClass(int num1, int num2) { score1 = num1; score2 = num2; } public void reset(int threshold) { if (score1 < threshold) // line 14 { score1 = 0; // line 16 } else if (score2 < threshold) // line 18 { score2 = 0; } } } Which of the following changes can be made so that the reset method works as intended?

In line 18, change else if to if.

Consider the following class, which models a bank account. The deposit method is intended to update the account balance by a given amount; however, it does not work as intended. public class BankAccount { private String accountOwnerName; private double balance; private int accountNumber; public BankAccount(String name, double initialBalance, int acctNum) { accountOwnerName = name; balance = initialBalance; accountNumber = acctNum; } public void deposit(double amount) { double balance = balance + amount; } } What is the best explanation of why the deposit method does not work as intended?

In the deposit method, the variable balance is declared as a local variable and is different from the instance variable balance.

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?

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

Consider the following class declaration. The changeWeather method is intended to update the value of the instance variable weather and return the previous value of weather before it was updated. public class WeatherInfo { private String city; private int day; private String weather; public WeatherInfo(String c, int d, String w) { city = c; day = d; weather = w; } public String changeWeather(String w) { /* missing code */ } } Which of the following options should replace /* missing code */ so that the changeWeather method will work as intended?

String prev = weather; weather = w; return prev;

Consider the following code segment, which is intended to calculate the average of two quiz scores. double avg = 15 + 20; avg /= 2; Which of the following best describes the behavior of the code segment?

The code segment stores 17.5 in avg because 17.5 is the result of the floating point division of 35.0 by 2.

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?

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

Consider the following class declaration. public class Student { private String name; private int age; public Student(String n, int a) { name = n; age = a; } public boolean isOlderThan5() { if (age > 5) { return true; } } } Which of the following best describes the reason this code segment will not compile?

The isOlderThan5 method is missing a return statement for the case when age is less than or equal to 5.

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?

balance = balance + amount; return balance;

Consider the following code segment, which uses properly declared and initialized int variables x and y and the String variable result. String result = ""; if (x < 5) { if (y > 0) { result += "a"; } else { result += "b"; } } else if (x > 10) { if (y < 0) { result += "c"; } else if (y < 10) { result += "d"; } result += "e"; } result += "f"; What is the value of result after the code segment is executed if x has the value 15 and y has the value 5 ?

def

Consider the following code segment. int num = 5; num *= 2; num %= 6; What is the value of num after the code segment is executed?

4

Consider the following code segment. int count = 0; int number = 20; while (number > 0) { number = number / 2; count++; } What will be the value of count after executing the code segment?

5

Consider the following class definition. public class Gadget { private static int status = 0; public Gadget() { status = 10; } public static void setStatus(int s) { status = s; } } The following code segment appears in a method in a class other than Gadget. Gadget a = new Gadget(); Gadget.setStatus(3); Gadget b = new Gadget(); Which of the following best describes the behavior of the code segment?

The code segment creates two Gadget objects a and b. The class Gadget's static variable status is set to 10, then to 3, and then back to 10.

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

The string "hello" will be printed four additional times because the inner loop will iterate one additional time for each iteration of the outer loop.

In the following expression, sunny and windy are properly declared and initialized boolean variables. !sunny && !windy Which of the following is equivalent to the expression above?

!(sunny || windy)

Consider the following class. public class Help { private int h; public Help(int newH) { h = newH; } public double getH() { return h; } } The getH method is intended to return the value of the instance variable h. The following code segment shows an example of creating and using a Help object. Help h1 = new Help(5); int x = h1.getH(); System.out.println(x); Which of the following statements best explains why the getH method does not work as intended?

The getH method should have a return type of int.

Consider the following code segment, which is intended to store the sum of all multiples of 10 between 10 and 100, inclusive (10 + 20 + ... + 100), in the variable total. int x = 100; int total = 0; while( /* missing code */ ) { total = total + x; x = x - 10; } Which of the following can be used as a replacement for /* missing code */ so that the code segment works as intended?

x >= 10

In the following expression, sweet, salty, and sour are properly declared and initialized boolean variables. sweet && (salty || sour) Which of the following expressions is equivalent to the expression above?

(sweet && salty) || (sweet && sour)

Consider the following code segment. System.out.println(hello); // Line 1 System.out.print(world); // Line 2 The code segment is intended to produce the following output but does not work as intended. hello world Which of the following changes can be made so that the code segment produces the intended output?

Enclosing hello in line 1 and world in line 2 in quotation marks

Each of the following code segments is intended to print the word Hello. Which of the following code segments works as intended? (I) System.out.print("Hello"); (II) System.out.print(Hello); (III) System.out.print(He);System.out.print(llo);

I

Consider the following code segment. int n = 6; for (int i = 1; i < n; i = i + 2) // Line 2 { System.out.print(i + " "); } Which of the following best explains how changing i < n to i <= n in line 2 will change the result?

There will be no change to the program output because the loop will iterate the same number of times.

Consider the following code segment: /* data type 1 */ x = 0.5; /* data type 2 */ y = true; Which of the following best describes the data types that should be used to replace /* data type 1 */ and /* data type 2 */ so that the code segment compiles without error?

The variable x should be declared as a double and the variable y should be declared as a boolean.

Consider the following class. The method getTotalSalaryAndBonus is intended to return an employee's total salary with the bonus added. The bonus should be doubled when the employee has 10 or more years of service. public class Employee { private String name; private double salary; private int yearsOfService; public Employee(String n, double sal, int years) { name = n; salary = sal; yearsOfService = years; } public double getTotalSalaryAndBonus(double bonus) { /* missing code */ } } Which of the following could replace /* missing code */ so that method getTotalSalaryAndBonus will work as intended?

if (yearsOfService >= 10) { bonus *= 2; } return salary + bonus;

In the following expression, j, k, and m are properly declared and initialized int variables. !((j == k) && (k > m)) Which of the following is equivalent to the expression above?

(j != k) || (k <= m)

Consider the following code segment. System.out.print("Ready"); // Line 1 System.out.print("Set"); // Line 2 System.out.print("Go!"); // Line 3 The code segment is intended to produce the following output but may not work as intended. Ready Set Go! Which change, if any, can be made so that the code segment produces the intended output?

Changing print to println in lines 1 and 2

The following class is used to represent shipping containers. Each container can hold a number of units equal to unitsPerContainer. public class UnitsHandler { private static int totalUnits = 0; private static int containers = 0; private static int unitsPerContainer = 0; public UnitsHandler(int containerSize) { unitsPerContainer = containerSize; } public static void update(int c) { containers = c; totalUnits = unitsPerContainer * containers; } } The following code segment appears in a method in a class other than UnitsHandler. Assume that no other code segments have created or modified UnitsHandler objects. UnitsHandler large = new UnitsHandler(100); UnitsHandler.update(8); Which of the following best describes the behavior of the code segment?

The code segment creates a UnitsHandler object called large and sets the static variables unitsPerContainer, containers, and totalUnits to 100, 8, and 800, respectively.

Consider the following class declaration. public class Student { private String firstName; private String lastName; private int age; public Student(String firstName, String lastName, int age) { firstName = firstName; lastName = lastName; age = age; } public String toString() { return firstName + " " + lastName; } } The following code segment appears in a method in a class other than Student. It is intended to create a Student object and then to print the first name and last name associated with that object. Student s = new Student("Priya", "Banerjee", -1); System.out.println(s); Which of the following best explains why the code segment does not work as expected?

The code segment will compile, but the instance variables will not be initialized correctly because the variable names firstName, lastName, and age refer to the local variables inside the constructor.

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?

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

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?

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

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?

The variable num is not defined in the addNum method.

Assume that the int variables a, b, c, and low have been properly declared and initialized. The code segment below is intended to print the sum of the greatest two of the three values but does not work in some cases. if (a > b && b > c) { low = c; } if (a > b && c > b) { low = b; } else { low = a; } System.out.println(a + b + c - low); For which of the following values of a, b, and c does the code segment NOT print the correct value?

a = 3, b = 2, c = 1

Consider the following code segment, which is intended to set the Boolean variable inRange to true if the integer value num is greater than min value and less than max value. Otherwise inRange is set to false. Assume that inRange, num, min, and max have been properly declared and initialized. boolean isBigger; boolean isSmaller; boolean inRange; if (num < max) { isSmaller = true; } else { isSmaller = false; } if (num > min) { isBigger = true; } else { isBigger = false; } if (isBigger == isSmaller) { inRange = true; } else { inRange = false; } Which of the following values of num, min, and max can be used to show that the code does NOT work as intended?

num = 50, min = 50, max = 50

The Employee class will contain a String attribute for an employee's name and a double attribute for the employee's salary. Which of the following is the most appropriate implementation of the class?

public class Employee { private String name; private double salary; // constructor and methods not shown }

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?

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

Consider the following code segment. String myString = new String("my string"); String yourString = new String(); yourString = "my string"; boolean dotEquals = myString.equals(yourString); boolean equalsEquals = (myString == yourString); System.out.print(dotEquals + " " + equalsEquals); What is printed as a result of executing the code segment?

true false

Consider the following class definition. public class ClassP { private String str; public ClassP(String newStr) { String str = newStr; } } The ClassP constructor is intended to initialize the str instance variable to the value of the formal parameter newStr. Which of the following statements best describes why the ClassP constructor does not work as intended?

The variable str should not be declared as a String in the constructor.

Consider the following code segment. int x; int y; x = 3; y = /* missing expression */; x = 1 + 2 * y; System.out.print(x); System.out.println(y); Which of the following can be used as a replacement for /* missing expression */ so that the code segment prints 94 ?

x + 1

Consider the following code segment. int x = 0; x++; x += 1; x = x + 1; x -= -1; System.out.println(x); What is printed when the code segment has been executed?

4

Consider the following code segment. String first = new String("duck"); String second = new String("duck"); String third = new String("goose"); if (first == second) { System.out.print("A"); } else if (second == third) { System.out.print("B"); } else if (first.equals(second)) { System.out.print("C"); } else if (second.equals(third)) { System.out.print("D"); } else { System.out.print("E"); } What is printed as a result of executing the code segment?

C

Consider the method digitSum below, which takes a positive integer parameter as input. public int digitSum(int num) { int total = 0; while (num > 0) { total += num % 10; num /= 10; } return total; } Which of the following code segments could replace the while loop in the method digitSum without changing the value returned by the method? (I.) for (int h = 0; h < num; h++) { total += num % 10; num /= 10; } (II.) for (int j = num; j > 0; j--) { total += j % 10; } (III.) for (int k = num; k > 0; k /= 10) { total += k % 10; }

III only

Consider the following class definition. public class Pet { private String name; private int age; public Pet(String str, int a) { name = str; age = a; } public getName() { return name; } } Which choice correctly explains why this class definition fails to compile

The accessor method is missing a return type.

Consider the following class definition. public class Person { private String name; private int feet; private int inches; public Person(String nm, int ft, int in) { name = nm; feet = ft; inches = in; } public int heightInInches() { return feet * 12 + inches; } public String getName() { return name; } public String compareHeights(person other) { if (this.heightInInches() < other.heightInInches()) { return name; } else if (this.heightInInches() > other.heightInInches()) { return other.getName(); } else return "Same" } } The following code segment appears in a method in a class other than Person. Person andy = new Person("Andrew", 5, 6); Person ben = new Person("Benjamin", 6, 5); System.out.println(andy.compareHeights(ben)); What, if anything, is printed as a result of executing the code segment?

Andrew

A teacher determines student percentages in a course as the points a student earns divided by the total points available in the grading period. Points are awarded only in whole number increments, but student percentages are to be stored as decimals. The following code segment appears in a program used to compute student percentages. Points that a student earns are stored in pointsEarned, the total points available in the grading period are stored in totalPoints, and the student percentage is stored in percentage. int pointsEarned; /* missing code */ Which of the following is most appropriate to replace /* missing code */ in the program?

int totalPoints;double percentage;

Consider the following class definition. public class Beverage { private int numOunces; private static int numSold = 0; public Beverage(int numOz) { numOunces = numOz; } public static void sell(int n) { /* implementation not shown */ } } Which of the following best describes the sell method's level of access to the numOunces and numSold variables?

numSold can be accessed and updated; numOunces cannot be accessed or updated.

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?

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

The Thing class below will contain a String attribute, a constructor, and the helper method, which will be kept internal to the class. public class Thing { /* missing code */ } Which of the following replacements for /* missing code */ is the most appropriate implementation of the class?

private String str; public Thing(String s) { /* implementation not shown */ } private void helper() { /* implementation not shown */ }

Consider the following code segment. String str1 = new String("Happy"); String str2 = new String("Happy"); System.out.print(str1.equals(str2) + " "); System.out.print(str2.equals(str1) + " "); System.out.print(str1 == str2); What is printed as a result of executing the code segment?

true true false

Consider the following code segment. String str = "AP-CSA"; for (int i = 0; i < str.length(); i++) { if (str.substring(i, i + 1).equals("A")) { System.out.print(i + " "); } } What is printed as a result of executing the code segment?

0 5

Consider the following two code segments, which are both intended to determine the longest of the three strings "pea", "pear", and "pearl" that occur in String str. For example, if str has the value "the pear in the bowl", the code segments should both print "pear" and if str has the value "the pea and the pearl", the code segments should both print "pearl". Assume that str contains at least one instance of "pea". (I.) if (str.indexOf("pea") >= 0) { System.out.println("pea"); } else if (str.indexOf("pear") >= 0) { System.out.println("pear"); } else if (str.indexOf("pearl") >= 0) { System.out.println("pearl"); } (II.) if (str.indexOf("pearl") >= 0) { System.out.println("pearl"); } else if (str.indexOf("pear") >= 0) { System.out.println("pear"); } else if (str.indexOf("pea") >= 0) { System.out.println("pea"); } Which of the following best describes the output produced by code segment I and code segment II?

Code segment II produces correct output for all values of str, but code segment I produces correct output only for values of str that contain "pea" but not "pear".

Which of the following arithmetic expressions evaluates to 1 ? (I) 2 / 5 % 3 (II) 2 / (5 % 3) (III) 2 / 5 + 1

II and III only

Consider the class definition below. The method levelUp is intended to increase a Superhero object's strength attribute by the parameter amount. The method does not work as intended. public class Superhero { private String name; private String secretIdentity; private int strength; public Superhero(String realName, String codeName) { name = realName; secretIdentity = codeName; strength = 5; } public int levelUp(int amount) // line 14 { strength += amount; // line 16 } } Which of the following changes should be made so that the levelUp method works as intended?

In line 14, levelUp should be declared as type void.

Consider the following code segment. boolean a = true; boolean b = true; System.out.print((b || (!a || b)) + " "); System.out.print(((!b || !a) && a) + " "); System.out.println(!(a && b) && b); What output is produced when this code segment is executed?

false true false

Consider the following method substringFound, which is intended to return true if a substring, key, is located at a specific index of the string phrase. Otherwise, it should return false. public boolean substringFound(String phrase, String key, int index) { String part = phrase.substring(index, index + key.length()); return part.equals(key); } Which of the following is the best precondition for index so that the method will return the appropriate result in all cases and a runtime error can be avoided?

0 <= index < phrase.length() - key.length()

The following code segment prints one or more characters based on the values of boolean variables b1 and b2. Assume that b1 and b2 have been properly declared and initialized. if (!b1 || b2) { System.out.print("A"); } else { System.out.print("B"); } if (!(b1 || b2)) { System.out.print("C"); } else { System.out.print("D"); } if (b1 && !b1) { System.out.print("E"); } If b1 and b2 are both initialized to true, what is printed when the code segment has finished executing?

AD

Consider the following two code segments. Assume that variables x and y have been declared as int variables and have been assigned integer values. (I.) int result = 0; if (x > y) { result = x - y; System.out.print(result); } else if (x < y) { result = y - x; System.out.print(result); } else { System.out.print(result); } (II.) if (x < y) { System.out.print(y - x); } else { System.out.print(x - y); } Which of the following correctly compares the outputs of the two code segments?

Code segment I and code segment II produce the same output for all values of x and y.

Consider the following code segment, which is intended to display 6.0. double fact1 = 1 / 2; double fact2 = 3 * 4; double product = fact1 * fact2; System.out.println(product); Which of the following best describes the error, if any, in the code segment?

Either the numerator or the denominator of the fraction 1 / 2 should be cast as double.

Consider the following code segment. System.out.print("Hello!"); System.out.println("How "); System.out.print("are "); System.out.print("you?"); What is printed as a result of executing the code segment?

Hello!How are you?

The volume of a cylinder is equal to the height times the area of the circular base. The area of the circular base is equal to π (pi) times the square of the radius. The code segment below is intended to compute and print the volume of a cylinder with radius r and height h. Assume that the double variables r, h, and pi have been properly declared and initialized. /* missing code */ System.out.print(volume); Which of the following can be used to replace /* missing code */ so that the code segment works as intended? (I) double baseArea = pi * r * r; double volume = baseArea * h; (II) double volume = pi * r * r; volume = volume * h; (III) double volume = pi * r * r * h;

I, II, and III

Consider the following code segment. int a = 1; int b = 0; int c = -1; if ((b + 1) == a) { b++; c += b; } if (c == a) { a--; b = 4; } What are the values of a, b, and c after this code segment has been executed?

a = 1, b = 1, and c = 0

Consider the following code segment. int a = 1; while (a <= 2) { int c = 1; while (/* missing condition */) { System.out.print("*"); c++; } a++; } The code segment is intended to print "******". Which of the following can be used to replace /* missing condition */ so that the code segment works as intended?

c <= 3


Set pelajaran terkait

Social Studies Review For Test 1/31/17

View Set

American Government Chapter 1,2,3

View Set

Chapter 1 - Nurse's Role in Health Assessment: Collecting & Analyzing Data

View Set

AP Human Geography Chapter 9 Agriculture

View Set

Chapter 11: Principle of Superposition, Principle of Original Horizontality, Principle of Lateral Continuity, Principle of Cross-Cutting Relationships, Principle of Inclusions

View Set

BUSMHR Exam 1 - Maintenance Roles VS Task Roles

View Set

Enlightenment/Neoclassicism/Romanticism

View Set

Java - Arrays, ArrayLists, Generics

View Set