AP Comp midterm study guide

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

Assume that the boolean variables a, b, c, and d have been declared and initialized. Consider the following expression. !( !( a && b ) || ( c || !d )) Which of the following is equivalent to the expression?

( a && b ) && ( !c && d )

Assume that a and b have been defined and initialized as int values. The expression ! ( ! (a != b ) && (b > 7) ) is equivalent to which of the following?

(a != b) || (b <= 7)

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?

1

Consider the following code segment. int value = 15; while (value < 28) { System.out.println(value); value++; } What are the first and last numbers output by the code segment?

15, 27

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?

161

Consider the following code segment. int one = 1; int two = 2; String zee = "Z"; System.out.println(one + two + zee); What is printed as a result of executing the code segment?

3Z

Consider the following method. public int getTheResult(int n) { int product = 1; for (int number = 1; number < n; number++) { if (number % 2 == 0) product *= number; } return product; } What value is returned as a result of the call getTheResult(8) ?

48

Consider the following code segment. String str = "CompSci"; System.out.println(str.substring(0, 3)); int num = str.length(); What is the value of num when the code segment is executed?

7

Consider the following code segment. String oldStr = "ABCDEF"; String newStr = oldStr.substring(1, 3) + oldStr.substring(4); System.out.println(newStr); What is printed as a result of executing the code segment?

BCEF

In the code segment below, assume that the int variable n has been properly declared and initialized. The code segment is intended to print a value that is 1 more than twice the value of n. /* missing code */ System.out.print(result); Which of the following can be used to replace /* missing code */ so that the code segment works as intended? int result = 2 * n;result = result + 1; int result = n + 1;result = result * 2; int result = (n + 1) * 2;

I only

Which of the following expressions evaluate to 3.5 ? I. (double) 2 / 4 + 3 II. (double) (2 / 4) + 3 III. (double) (2 / 4 + 3)

I only

Consider the following code segments. I. int k = 1; while (k < 20) { if (k % 3 == 1) System.out.print( k + " "); k = k + 3; } II. for (int k = 1; k < 20; k++) { if (k % 3 == 1) System.out.print( k + " "); } III. for (int k = 1; k < 20; k = k + 3) { System.out.print( k + " "); } Which of the code segments above will produce the following output? 1 4 7 10 13 16 19

I, II, and III

Consider the following class declaration. public class GameClass { private int numPlayers; private boolean gameOver; public Game() { numPlayers = 1; gameOver = false; } public void addPlayer() { numPlayers++; } public void endGame() { gameOver = true; } } Assume that the GameClass object game has been properly declared and initialized in a method in a class other than GameClass. Which of the following statements are valid? I. game.numPlayers++; II. game.addPlayer(); III. game.gameOver(); IV. game.endGame();

II and IV only

Consider the following method, which is intended to calculate and return the expression square root of ((x+y)^2)/(abs value of a-b) public double calculate(double x, double y, double a, double b) { return /* missing code */; } Which of the following can replace /* missing code */ so that the method works as intended?

Math.sqrt(Math.pow(x + y, 2) / Math.abs(a - b))

Assume that the boolean variables a and b have been declared and initialized. Consider the following expression. (a && (b || !a)) == a && b Which of the following best describes the conditions under which the expression will evaluate to true?

Only when b is true

Consider the following code segment. int x = /* some integer value */ ; int y = /* some integer value */ ; boolean result = (x < y); result = ( (x >= y) && !result ); Which of the following best describes the conditions under which the value of result will be true after the code segment is executed?

Only when x>=y

Consider the following code segment. int w = 1; int x = w / 2; double y = 3; int z = (int) (x + y); Which of the following best describes the results of compiling the code segment?

The code segment compiles without error.

Consider the following code segment. The code is intended to read nonnegative numbers and compute their product until a negative number is read; however, it does not work as intended. (Assume that the readInt method correctly reads the next number from the input stream.) int k = 0; int prod = 1; while (k >= 0) { System.out.print("enter a number: "); k = readInt(); // readInt reads the next number from input prod = prod * k; } System.out.println("product: " + prod); Which of the following best describes the error in the program?

The negative number entered to signal no more input is included in the product.

Consider the following statement. Assume that a and b are properly declared and initialized boolean variables. boolean c = (a && b) || (!a && b); Under which of the following conditions will c be assigned the value false ?

When b has the value false

Assume that x and y are boolean variables and have been properly initialized. (x && y) || !(x && y) The result of evaluating the expression above is best described as

always true

Consider the following method, biggest, which is intended to return the greatest of three integers. It does not always work as intended. Which of the following best describes the error in the method?

biggest may not work correctly when a and b have equal values.

Consider the following statement, which assigns a value to b1. boolean b1 = true && (17 % 3 == 1); Which of the following assigns the same value to b2 as the value stored in b1 ?

boolean b2 = false && (17 % 3 == 2);

Assume that x and y are boolean variables and have been properly initialized. (x && y) && !(x || y) Which of the following best describes the result of evaluating the expression above?

false always

Consider the following code segment. if (a < b || c != d) { System.out.println("dog"); } else { System.out.println("cat"); } Assume that the int variables a, b, c, and d have been properly declared and initialized. Which of the following code segments produces the same output as the given code segment for all values of a, b, c, and d ?

if (a >= b && c == d) { System.out.println("cat"); } else { System.out.println("dog"); }

Which of the following code segments produces the output "987654321" ?

int num = 10; while (num > 1) { num--; System.out.print(num); }

Consider the following method. Which of the following represents the value returned as a result of the call compute (n, k) ?

n^k

Consider the following static method. public static int calculate(int x) { x = x + x; x = x + x; x = x + x; return x; } Which of the following can be used to replace the body of calculate so that the modified version of calculate will return the same result as the original version for all x ?

return 8 * x;

Consider the following method that is intended to determine if the double values d1 and d2 are close enough to be considered equal. For example, given a tolerance of 0.001, the values 54.32271 and 54.32294 would be considered equal. Which of the following should replace / * missing code * / so that almostEqual will work as intended?

return Math.abs(d1 - d2) <= tolerance;

Consider the following code segment. String alpha = new String("APCS"); String beta = new String("APCS"); String delta = alpha; System.out.println(alpha.equals(beta)); System.out.println(alpha == beta); System.out.println(alpha == delta); What is printed as a result of executing the code segment?

true false true

Consider the following declarations. int valueOne, valueTwo; Assume that valueOne and valueTwo have been initialized. Which of the following evaluates to true if valueOne and valueTwo contain the same value?

valueOne == valueTwo

Assume that x and y are boolean variables and have been properly initialized. (x || y) && x Which of the following always evaluates to the same value as the expression above?

x

Consider the following code segment in which the int variable x has been properly declared and initialized. if (x % 2 == 1) { System.out.println("YES"); } else { System.out.println("NO"); } Assuming that x is initialized to the same positive integer value as the original, which of the following code segments will produce the same output as the original code segment? I. if (x % 2 == 1) { System.out.print("YES"); } if (x % 2 == 0) { System.out.println("NO"); } II. if (x % 2 == 1) { System.out.println("YES"); } else if (x % 2 == 0) { System.out.println("NO"); } else { System.out.println("NONE"); } III. boolean test = x % 2 == 0; if (test) { System.out.println("YES"); } else { System.out.println("NO"); }

I and II only

Consider the following method. public void doSomething() { System.out.println("Something has been done"); } Each of the following statements appears in a method in the same class as doSomething. Which of the following statements are valid uses of the method doSomething ? I. doSomething(); II. String output = doSomething(); III. System.out.println(doSomething());

I only

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?

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

Assume that x and y have been declared and initialized with int values. Consider the following Java expression. (y>10000) || (x>1000 && x<1500) Which of the following is equivalent to the expression given above?

(y > 10000 | | x > 1000) && (y > 10000 | | x < 1500)

Consider the following code segment. double x = (int) (5.5 - 2.5); double y = (int) 5.5 - 2.5; System.out.println(x - y); What is printed as a result of executing the code segment?

0.5

Consider the following code segment. String str = "0"; str += str + 0 + 8; System.out.println(str); What is printed as a result of executing the code segment?

0008

Consider the following methods, which appear in the same class. public void slope(int x1, int y1, int x2, int y2) { int xChange = x2 - x1; int yChange = y2 - y1; printFraction(yChange, xChange); } public void printFraction(int numerator, int denominator) { System.out.print(numerator + "/" + denominator); } Assume that the method call slope(1, 2, 5, 10) appears in a method in the same class. What is printed as a result of the method call?

8/4

Consider the following code segment. int a = 5; int b = 4; int c = 2; a *= 3; b += a; b /= c; System.out.print(b); What is printed when the code segment is executed?

9

Consider the following method. public void conditionalTest(int a, int b) { if ((a > 0) && (b > 0)) { if (a > b) System.out.println("A"); else System.out.println("B"); } else if ((b < 0) || (a < 0)) System.out.println("C"); else System.out.println("D"); } What is printed as a result of the call conditionalTest(3, -2)?

C

In the code segment below, assume that the int variables a and b have been properly declared and initialized. int c = a; int d = b; c += 3; d--; double num = c; num /= d; Which of the following best describes the behavior of the code segment?

The code segment stores the value of (a + 3) / (b - 1) in the variable num

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?

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

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

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

Consider the following method. Which of the following best describes the value returned from a call to doWhat ?

The sum of all odd integers between 1 and num, inclusive

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?

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

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

Assume obj1 and obj2 are object references. Which of the following best describes when the expression obj1 == obj2 is true?

When obj1 and obj2 refer to the same object

The question refer to the code from the GridWorld case study. Consider the following code segment. Location loc1 = new Location(3, 3); Location loc2 = new Location(3, 2); if (loc1.equals(loc2.getAdjacentLocation(Location.EAST))) System.out.print("aaa"); if (loc1.getRow() == loc2.getRow()) System.out.print("XXX"); if (loc1.getDirectionToward(loc2) == Location.EAST) System.out.print("555"); What will be printed as a result of executing the code segment?

aaaXXX

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;

A code segment (not shown) is intended to determine the number of players whose average score in a game exceeds 0.5. A player's average score is stored in avgScore, and the number of players who meet the criterion is stored in the variable count. Which of the following pairs of declarations is most appropriate for the code segment described?

double avgScore; int count;

Consider the following method. public double myMethod(int a, boolean b) { /* implementation not shown */ } Which of the following lines of code, if located in a method in the same class as myMethod, will compile without error?

double result = myMethod(0, false);

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?

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

Consider the following methods, which appear in the same class. public int function1(int i, int j) { return i + j; } public int function2(int i, int j) { return j - i; } Which of the following statements, if located in a method in the same class, will initialize the variable x to 11?

int x = function1(4, 5) + function2(1, 3);

Consider the following class definition. public class Example { private int x; // Constructor not shown. } Which of the following is a correct header for a method of the Example class that would return the value of the private instance variable x so that it can be used in a class other than Example ?

public int getX()

Consider the following method, between, which is intended to return true if x is between lower and upper, inclusive, and false otherwise. // precondition: lower <= upper // postcondition: returns true if x is between lower and upper, // inclusive; otherwise, returns false public boolean between(int x, int lower, int upper) { /* missing code */ } Which of the following can be used to replace /* missing code */ so that between will work as intended?

return (x >= lower) && (x <= upper);

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 ?

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

Assume that a, b, and c are boolean variables that have been properly declared and initialized. Which of the following boolean expressions is equivalent to !(a && b) || c ?

!a || !b || c

Consider the following two code segments. Assume that the int variables m and n have been properly declared and initialized and are both greater than 0. for (int i = 0; i < m * n; i++){ System.out.print("A");} for (int j = 1; j <= m; j++){ for (int k = 1; k < n; k++) { System.out.print("B"); }} Assume that the initial values of m and n are the same in code segment I as they are in code segment II. Which of the following correctly compares the number of times that "A" and "B" are printed when each code segment is executed?

"A" is printed m more times than "B".

Consider the following code segment. String str1 = new String("Advanced Placement"); String str2 = new String("Advanced Placement"); if (str1.equals(str2) && str1 == str2) { System.out.println("A"); } else if (str1.equals(str2) && str1 != str2) { System.out.println("B"); } else if (!str1.equals(str2) && str1 == str2) { System.out.println("C"); } else if (!str1.equals(str2) && str1 != str2) { System.out.println("D"); } What, if anything, is printed when the code segment is executed?

B

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.

The code segment below is intended to calculate the circumference c of a circle with the diameter d of 1.5. The circumference of a circle is equal to its diameter times pi. /* missing declarations */ c = pi * d; Which of the following variable declarations are most appropriate to replace /* missing declarations */ in this code segment?

final double pi = 3.14159; double d = 1.5; double c;

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 a = 5; int b = 2; double c = 3.0; System.out.println(5 + a / b * c - 1); What is printed when the code segment is executed?

10.0

Consider the following code segment. double d1 = 10.0; Double d2 = 20.0; Double d3 = new Double(30.0); double d4 = new Double(40.0); System.out.println(d1 + d2 + d3.doubleValue() + d4); What, if anything, is printed when the code segment is executed?

100.0

A pair of number cubes is used in a game of chance. Each number cube has six sides, numbered from 1 to 6, inclusive, and there is an equal probability for each of the numbers to appear on the top side (indicating the cube's value) when the number cube is rolled. The following incomplete statement appears in a program that computes the sum of the values produced by rolling two number cubes. int sum = / * missing code * / ; Which of the following replacements for /* missing code */ would best simulate the value produced as a result of rolling two number cubes?

2 + (int) (Math.random() * 6) + (int) (Math.random() * 6)

Consider the following code segment. double num = 9 / 4; System.out.print(num); System.out.print(" "); System.out.print((int) num); What is printed as a result of executing the code segment?

2.0 2

Consider the following class declaration public class SomeClass { private int num; public SomeClass(int n) { num = n; } public void increment(int more) { num = num + more; } public int getNum() { return num; } } The following code segment appears in another class. SomeClass one = new SomeClass(100); SomeClass two = new SomeClass(100); SomeClass three = one; one.increment(200); System.out.println(one.getNum() + " " + two.getNum() + " " + three.getNum()); What is printed as a result of executing the code segment?

300 100 300

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?

5

Consider the following code segment. double x = 4.5; int y = (int) x * 2; System.out.print(y); What is printed as a result of executing the code segment?

8

Consider the following class definition. public class ExamScore { private String studentId; private double score; public ExamScore(String sid, double s) { studentId = sid; score = s; } public double getScore() { return score; } public void bonus(int b) { score += score * b/100.0; } } Assume that the following code segment appears in a class other than ExamScore. ExamScore es = new ExamScore("12345", 80.0); es.bonus(5); System.out.println(es.getScore()); What is printed as a result of executing the code segment?

84.0

Consider the following code segment. int a = 5; int b = 8; int c = 3; System.out.println(a + b / c * 2); What is printed as a result of executing this code?

9

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?

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

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 ?

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.

A teacher put three bonus questions on a test and awarded 5 extra points to anyone who answered all three bonus questions correctly and no extra points otherwise. Assume that the boolean variables bonusOne, bonusTwo, and bonusThree indicate whether a student has answered the particular question correctly.Each variable was assigned true if the answer was correct and false if the answer was incorrect. Which of the following code segments will properly update the variable grade based on a student's performance on the bonus questions? I. if (bonusOne && bonusTwo && bonusThree) grade += 5; II. if (bonusOne || bonusTwo || bonusThree) grade += 5; III. if (bonusOne) grade += 5; if (bonusTwo) grade += 5; if (bonusThree) grade += 5;

I only

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?

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

Consider the following Boolean expressions. I. A && B II. !A && !B Which of the following best describes the relationship between values produced by expression I and expression II?

Expression I and expression II evaluate to the same value only when A and B differ.

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

I and II only

Consider the following code segment. int x = 5; int y = 6; /* missing code */ z = (x + y) / 2; Which of the following can be used to replace /* missing code */ so that the code segment will compile? I. int z = 0; II. int z; III. boolean z = false;

I and II only

Assume that a, b, and c are variables of type int. Consider the following three conditions. I. (a == b) && (a == c) && (b == c) II. (a == b) || (a == c) || (b == c) III. ((a - b) * (a - c) * (b - c)) == 0 Assume that subtraction and multiplication never overflow. Which of the conditions above is (are) always true if at least two of a, b, and c are equal?

II and III

Consider the following class. public class SomeMethods {public void one(int first) { / * implementation not shown * / } public void one(int first, int second) { / * implementation not shown * / } public void one(int first, String second) { / * implementation not shown * / } } Which of the following methods can be added to the SomeMethods class without causing a compile-time error? public void one(int value){ / * implementation not shown * / } public void one (String first, int second) { / * implementation not shown * / } public void one (int first, int second, int third) { / * implementation not shown * / }

II and III only

Consider the following class definitions. public class Person { private String name; public String getName() { return name; } } public class Book { private String author; private String title; private Person borrower; public Book(String a, String t) { author = a; title = t; borrower = null; } public void printDetails() { System.out.print("Author: " + author + " Title: " + title); if ( /* missing condition */ ) { System.out.println(" Borrower: " + borrower.getName()); } } public void setBorrower(Person b) { borrower = b; } } Which of the following can replace /* missing condition */ so that the printDetails method CANNOT cause a run-time error? !borrower.equals(null) borrower != null borrower.getName() != null

II only

Consider the following code segment, which is intended to find the average of two positive integers, x and y. int x; int y; int sum = x + y; double average = (double) (sum / 2); Which of the following best describes the error, if any, in the code segment?

In the expression (double) (sum / 2) , the cast to double is applied too late, so the average will be greater than the expected result for odd values of sum .

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

Consider the following code segments, which are each intended to convert grades from a 100-point scale to a 4.0-point scale and print the result. A grade of 90 or above should yield a 4.0, a grade of 80 to 89 should yield a 3.0, a grade of 70 to 79 should yield a 2.0, and any grade lower than 70 should yield a 0.0. Assume that grade is an int variable that has been properly declared and initialized. Code Segment I double points = 0.0; if (grade > 89) { points += 4.0; } else if (grade > 79) { points += 3.0; } else if (grade > 69) { points += 2.0; } else { points += 0.0; } System.out.println(points); Code Segment II double points = 0.0; if (grade > 89) { points += 4.0; } if (grade > 79) { grade += 3.0; } if (grade > 69) { points += 2.0; } if (grade < 70) { points += 0.0; } System.out.println(points); Which of the following statements correctly compares the values printed by the two methods?

The two code segments print the same value only when grade is below 80.

Which of the following best describes the value of the Boolean expression shown below? a && !(b || a)

The value is always false.

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.

Consider the following methods. /** Precondition: a > 0 and b > 0 */ public static int methodOne(int a, int b) { int loopCount = 0; for (int i = 0; i < a / b; i++) { loopCount++; } return loopCount; } /** Precondition: a > 0 and b > 0 */ public static int methodTwo(int a, int b) { int loopCount = 0; int i = 0; while (i < a) { loopCount++; i += b; } return loopCount; } Which of the following best describes the conditions under which methodOne and methodTwo return the same value?

When a % b is equal to zero

Which of the following can be used to replace /* missing code */ so that moveActorToNewGrid will work as intended?

anActor.removeSelfFromGrid(); anActor.putSelfInGrid(newGrid, loc);

Consider the following two code segments where the int variable choice has been properly declared and initialized. Code Segment A if (choice > 10) { System.out.println("blue"); } else if (choice < 5) { System.out.println("red"); } else { System.out.println("yellow"); } Code Segment B if (choice > 10) { System.out.println("blue"); } if (choice < 5) { System.out.println("red"); } else { System.out.println("yellow"); } Assume that both code segments initialize choice to the same integer value. Which of the following best describes the conditions on the initial value of the variable choice that will cause the two code segments to produce different output?

choice>10

Consider the following code segment. String temp = "comp"; System.out.print(temp.substring(0) + " " + temp.substring(1) + " " + temp.substring(2) + " " + temp.substring(3)); What is printed when the code segment is executed?

comp omp mp p

Consider the following method, which is intended to return true if at least one of the three strings s1, s2, or s3 contains the substring "art". Otherwise, the method should return false. Which of the following method calls demonstrates that the method does not work as intended?

containsArt ("rattrap", "similar", "today")

The Student class has been defined to store and manipulate grades for an individual student. The following methods have been defined for the class. /* Returns the sum of all of the student's grades */ public double sumOfGrades() { /* implementation not shown */ } /* Returns the total number of grades the student has received */ public int numberOfGrades() { /* implementation not shown */ } /* Returns the lowest grade the student has received */ public double lowestGrade() { /* implementation not shown */ } Which of the following statements, if located in a method in the Student class, will determine the average of all of the student's grades except for the lowest grade and store the result in the double variable newAverage ?

newAverage = (sumOfGrades() - lowestGrade()) / (numberOfGrades() - 1);

Assume that object references one, two, and three have been declared and instantiated to be of the same type. Assume also that one == two evaluates to true and that two.equals(three) evaluates to false. Consider the following code segment. if (one.equals(two)) { System.out.println("one dot equals two"); } if (one.equals(three)) { System.out.println("one dot equals three"); } if (two == three) { System.out.println("two equals equals three"); } What, if anything, is printed as a result of executing the code segment?

one dot equals two

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 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 */ }

Consider the following code segment, which is intended to simulate a random process. The code is intended to set the value of the variable event to exactly one of the values 1, 2, or 3, depending on the probability of an event occurring. The value of event should be set to 1 if the probability is 70 percent or less. The value of event should be set to 2 if the probability is greater than 70 percent but no more than 80 percent. The value of event should be set to 3 if the probability is greater than 80 percent. The variable randomNumber is used to simulate the probability of the event occurring. int event = 0; if (randomNumber <= 0.70) { event = 1; } if (randomNumber <= 0.80) { event = 2; } else { event = 3; } The code does not work as intended. Assume that the variable randomNumber has been properly declared and initialized. Which of the following initializations for randomNumber will demonstrate that the code segment will not work as intended?

randomNumber= 0.70

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


Set pelajaran terkait

Accounting Chapter 1 Pearson MyLab

View Set

Differential and Integral Calculus Terms and Elements - ME Boards Exam

View Set

Midterm Exam for Abnormal Psychology

View Set

Types of Life Insurance Policies QUIZ

View Set

Digital Media IA Review Certification Exam CP

View Set