CSA Midterm Review
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 an integer array nums, which has been properly declared and initialized with one or more values. Which of the following code segments counts the number of negative values found in nums and stores the count in counter ? int counter = 0;int i = -1;while (i <= nums.length - 2){ i++; if (nums[i] < 0) { counter++; }} int counter = 0;for (int i = 1; i < nums.length; i++){ if (nums[i] < 0) { counter++; }} int counter = 0;for (int i : nums){ if (nums[i] < 0) { counter++; }} A I only B II only C I and II only D I and III only E I, II, and III
I only
Consider the following method, isSorted, which is intended to return true if an array of integers is sorted in nondecreasing order and to return false otherwise. Which of the following can be used to replace /* missing code */ so that isSorted will work as intended? A I only B II only C III only D I and II only E I and III only
I only
The code segment below is intended to print the length of the shortest string in the array wordArray. Assume that wordArray contains at least one element. int shortest = /* missing value */; for (String word : wordArray) { if (word.length() < shortest) { shortest = word.length(); } } System.out.println(shortest); Which of the following should be used as the initial value assigned to shortest so that the code segment works as intended? A Integer.MAX_VALUE B Integer.MIN_VALUE C 0 D word.length() E wordArray.length
Integer.MAX_VALUE
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? A Only when x < y B Only when x >= y C Only when x and y are equal D The value will always be true. E The value will never be true.
Only when x >= y
The following code segment appears in a method in a class other than Something. Something s = new Something(); Something.increment(); Which of the following best describes the behavior of the code segment? A The code segment does not compile because the increment method should be called on an object of the class Something, not on the class itself. B The code segment creates a Something object s. The class Something's static variable count is initially 0, then increased by 1. C The code segment creates a Something object s. The class Something's static variable count is initially 0, then increased by 5, then increased by 1. D The code segment creates a Something object s. After executing the code segment, the object s has a count value of 1. E The code segment creates a Something object s. After executing the code segment, the object s has a count value of 5.
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 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 ? A for (int y = 0; y <= 2; y++) B for (int y = 0; y < 3; y++) C for (int y = 2; y >= 0; y--) D for (int y = 3; y > 0; y--) E for (int y = 0; y < x; y++)
for (int y = 0; y < x; y++)
Which of the following would be the best specification for a Circle method isInside that determines whether a Point lies inside this Circle? A public boolean isInside() B public void isInside(boolean found) C public boolean isInside(Point p) D public void isInside(Point p, boolean found) E public boolean isInside(Point p, Point center, double radius)
public boolean isInside(Point p)
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? A randomNumber = 0.70; B randomNumber = 0.80; C randomNumber = 0.85; D randomNumber = 0.90; E randomNumber = 1.00;
randomNumber = 0.70;
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? A false false false B false false true C true false false D true false true E true true true
true false true
Consider the following method. Method allEven is intended to return true if all elements in array arr are even numbers; otherwise, it should return false. public boolean allEven(int[] arr) { boolean isEven = /* expression */ ; for (int k = 0; k < arr.length; k++) { /* loop body */ } return isEven; } Which of the following replacements for /* expression */ and /* loop body */ should be used so that method allEven will work as intended? A /* expression *//* loop body */false if ((arr[k] % 2) == 0) isEven = true; B /* expression *//* loop body */false if ((arr[k] % 2) != 0) isEven = false; else isEven = true; C /* expression *//* loop body */true if ((arr[k] % 2) != 0) isEven = false; D /* expression *//* loop body */true if ((arr[k] % 2) != 0) isEven = false; else isEven = true; E /* expression *//* loop body */true if ((arr[k] % 2) == 0) isEven = false; else isEven = true;
true if ((arr[k] % 2) != 0) isEven = false;
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? A valueOne.equals((Object) valueTwo) B valueOne == valueTwo C valueOne.compareTo((Object) valueTwo) == 0 D valueOne.compareTo(valueTwo) == 0 E valueOne.equals(valueTwo)
valueOne == valueTwo
Consider the following class definition. public class Box { private double weight; /** Postcondition: weight is initialized to w. */ public Box(double w) { /* implementation not shown */ } public double getWeight() { return weight; } public void addWeight(double aw) { /* missing statement */ } } The following code segment, which appears in a class other than Box, is intended to create a Box object b1 with a weight of 2.2 units and then increase the weight of b1 by 1.5 units. Box b1 = new Box(2.2); b1.addWeight(1.5); Which of the following statements could replace /* missing statement */ so that the code segment works as intended? A aw += weight; B aw += getWeight(); C weight += aw; D weight += getWeight(); E return weight + aw;
weight += aw;
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 "? A while (k < 3) B while (k < 4) C while (k < 5) D while (k <= 4) E while (k <= 5)
while (k < 4)
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? A while (r <= 100) B while (sum <= 100) C while (r < 101) D while (r <= 101) E while (sum <= 101)
while (r <= 101)
Assume that x and y are boolean variables and have been properly initialized. Which of the following always evaluates to the same value as the expression above? A x B y C x && y D x | | y E x != y
x
Consider the following Boolean expression in which the int variables x and y have been properly declared and initialized. (x <= 10) == (y > 25) Which of the following values for x and y will result in the expression evaluating to true ? A x = 8 and y = 25 B x = 10 and y = 10 C x = 10 and y = 30 D x = 15 and y = 30 E x = 25 and y = 30
x = 10 and y = 30
Consider the following code segment. int x = 3; int y = -1; if (x - 2 > y) { x -= y; } if (y + 3 >= x) { y += x; } System.out.print("x = " + x + " y = " + y); What is printed as a result of the execution of the code segment? A x = -1 y = -1 B x = 2 y = 1 C x = 3 y = 2 D x = 4 y = -1 E x = 4 y = 3
x = 4 y = -1
Consider the following code segment. int[] arr = {1, 2, 3, 4, 5, 6, 7}; for (int i = 1; i < arr.length; i += 2) { arr[i] = arr[i - 1]; } Which of the following represents the contents of the array arr after the code segment is executed? A {0, 1, 2, 3, 4, 5, 6} B {1, 1, 1, 1, 1, 1, 1} C {1, 1, 3, 3, 5, 5, 7} D {1, 2, 3, 4, 5, 6, 7} E {2, 2, 4, 4, 6, 6, 7}
{1, 1, 3, 3, 5, 5, 7}
Which of the following changes should be made so that method findLongest will work as intended? A Insert the statement lenCount = 0; between lines 2 and 3. B Insert the statement lenCount = 0; between lines 8 and 9. C Insert the statement lenCount = 0; between lines 10 and 11. D Insert the statement lenCount = 0; between lines 11 and 12. E Insert the statement lenCount = 0; between lines 12 and 13.
Insert the statement lenCount = 0; between lines 12 and 13.
Method findMax is intended to return the largest value in the array arr. Which of the following best describes the conditions under which the method findMax will not work as intended? A The largest value in arr occurs only once and is in arr[0]. B The largest value in arr occurs only once and is in arr[arr.length - 1]. C The largest value in arr is negative. D The largest value in arr is zero. E The largest value in arr occurs more than once.
The largest value in arr is negative.
Consider the following code segment. int x = 7; int y = 4; boolean a = false; boolean b = false; if (x > y) { if (x % y >= 3) { a = true; x -= y; } else { x += y; } } if (x < y) { if (y % x >= 3) { b = true; x -= y; } else { x += y; } } What are the values of a, b, and x after the code segment has been executed? A a = true, b = true, x = -1 B a = true, b = false, x = 3 C a = true, b = false, x = 7 D a = false, b = true, x = 3 E a = false, b = false, x = 11
a = true, b = false, x = 7
Assume that a and b are variables of type int. The expression !(a < b) && !(a > b) is equivalent to which of the following? A true B false C a == b D a != b E !(a < b) && (a > b)
a == b
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 A always true B always false C true only when x is true and y is true D true only when x and y have the same value E true only when x and y have different values
always true
Which of the following can replace /* missing condition 1 */ and /* missing condition 2 */ so the code segment works as intended? A /* missing condition 1 *//* missing condition 2 */arr[j] == arr[k]valCount > modeCount B /* missing condition 1 *//* missing condition 2 */arr[j] == arr[k]modeCount > valCount C /* missing condition 1 *//* missing condition 2 */arr[j] != arr[k] valCount > modeCount D /* missing condition 1 *//* missing condition 2 */arr[j] != arr[k]modeCount > valCount E /* missing condition 1 *//* missing condition 2 */arr[j] != arr[k]modeCount != valCount
arr[j] == arr[k] valCount > modeCount
Consider the following incomplete method that is intended to return an array that contains the contents of its first array parameter followed by the contents of its second array parameter. Which of the following expressions can be used to replace /* index */ so that append will work as intended? j B k C k + a1.length - 1 D k + a1.length E k + a1.length + 1
k + a1.length
Assume that the array arr has been defined and initialized as follows. Which of the following will correctly print all of the odd integers contained in arr but none of the even integers contained in arr ?
x%2 != 0
Consider the following code segment. Which of the following represents the contents of arr as a result of executing the code segment? A {1, 2, 3, 4, 5, 6, 7} B {1, 2, 3, 5, 6, 7} C {1, 2, 3, 5, 6, 7, 7} D {1, 2, 3, 5, 6, 7, 8} E {2, 3, 4, 5, 6, 7, 7}
{1, 2, 3, 5, 6, 7, 7}
Consider the following code segment. int start = 4; int end = 5; boolean keepGoing = true; if (start < end && keepGoing) { if (end > 0) { start += 2; end++; } else { end += 3; } } if (start < end) { if (end == 0) { end += 2; start++; } else { end += 4; } } What is the value of end after the code segment is executed? A 5 B 6 C 9 D 10 E 16
6
Consider the following class definitions. public class MenuItem { private double price; public MenuItem(double p) { price = p; } public double getPrice() { return price; } public void makeItAMeal() { Combo meal = new Combo(this); price = meal.getComboPrice(); } } public class Combo { private double comboPrice; public Combo(MenuItem item) { comboPrice = item.getPrice() + 1.5; } public double getComboPrice() { return comboPrice; } } The following code segment appears in a class other than MenuItem or Combo. MenuItem one = new MenuItem(5.0); one.makeItAMeal(); System.out.println(one.getPrice()); What, if anything, is printed as a result of executing the code segment? A 1.5 B 5.0 C 6.5 D 8.0 E Nothing is printed because the code will not compile.
6.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? A 45 B 50 C 55 D 60 E 66
60
Assume that the array nums has been declared and initialized as follows. int [ ] nums = { 3, 6, 1, 0, 1, 4, 2}; What value will be returned as a result of the call mystery(nums) ? A 5 B 6 C 7 D 10 E 17
7
Consider the following code segment. double regularPrice = 100; boolean onClearance = true; boolean hasCoupon = false; double finalPrice = regularPrice; if(onClearance) { finalPrice -= finalPrice * 0.25; } if(hasCoupon) { finalPrice -= 5.0; } System.out.println(finalPrice); What is printed as a result of executing the code segment? A 20.0 B 25.0 C 70.0 D 75.0 E 95.0
75.0
Consider the following method. Which of the following test data sets would test each possible output for the method? A 8, 9, 12 B 7, 9, 11 C 8, 9, 11 D 8, 11, 13 E 7, 9, 10
8, 9, 11
Consider the problem of finding the maximum value in an array of integers. The following code segments are proposed solutions to the problem. Assume that the variable arr has been defined as an array of int values and has been initialized with one or more values. Which of the code segments will always correctly assign the maximum element of the array to the variable max ? A I only B II only C III only D II and III only E I, II, and III
I, II and III
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? A I only B II only C III only D I and II E II and III
II and III
When the code segment is executed, the string "CarHouseGorilla" is printed.The following three code segments have been proposed as replacements for / * missing code * /. Which of these code segments can be used to replace /* missing code */ so that concatWords will work as intended? A I only B II only C III only D I and II E II and III
II and III
for (int k = 0; k < data.length; k++){ result += k;} for (int d : data){ result += d;} for (int k = 0; k < data.length; k++){ result += data[k];} Which of the replacements for /* missing code */ could be used so that total will work as intended? A I only B II only C III only D I and II E II and III
II and III
Which of the following is the best postcondition for checkArray ? A Returns the index of the first element in array array whose value is greater than array [loc] B Returns the index of the last element in array array whose value is greater than array [loc] C Returns the largest value in array array D Returns the index of the largest value in array array E Returns the index of the largest value in the second half of array array
Returns the index of the largest value in array array
Consider a modification to the method that eliminates the else from line 7 so that line 7 becomes if (x % 2 == 0) // Modified line 7 For which of the following values of x would the return values of the original method and the modified method differ? A 0 B 5 C 14 D 22 E 25
22
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 a && b && c B a || b || c C !a && !b || c D !a && !b && c E !a || !b || c
!a || !b || c
Consider the following incomplete method, which is intended to return true if the value of y is between the values of the other two parameters and false otherwise. /** Precondition: x, y, and z have 3 different values. */ public static boolean compareThree(int x, int y, int z) { return /* missing condition */ ; } The following table shows the results of several calls to compareThree. CallResultcompareThree(4, 5, 6)truecompareThree(6, 5, 4)truecompareThree(5, 4, 6)falsecompareThree(3, 4, 4)violates precondition Which of the following can be used to replace /* missing condition */ so that compareThree will work as intended when called with parameters that satisfy its precondition? A (x > y) && (x > z) B (x > y) && (y > z) C (x > y) || (y > z) D (x > y) == (y > z) E (x > y) != (y > z)
(x > y) == (y > z)
Assume that x and y have been declared and initialized with int values. Consider the following Java expression. Which of the following is equivalent to the expression given above? A (y > 10000 | | x > 1000) && (y > 10000 | | x < 1500) B (y > 10000 | | x > 1000) | | (y > 10000 | | x < 1500) C (y > 10000) && (x > 1000 | | x < 1500) D (y > 10000 && x > 1000) | | (y > 10000 && x < 1500) E (y > 10000 && x > 1000) && (y > 10000 && x < 1500)
(y > 10000 | | x > 1000) && (y > 10000 | | x < 1500)
The following code segment appears in a class other than SomeClass. SomeClass first = new SomeClass(10); SomeClass second = new SomeClass(20); SomeClass third = new SomeClass(30); first.incrementY(); second.incrementY(10); System.out.println(third.getY()); What is printed as a result of executing the code segment if the code segment is the first use of a SomeClass object? A 0 B 1 C 11 D 14 E 30
14
Consider the following code segment. int[] arr = {4, 2, 9, 7, 3}; for (int k : arr) { k = k + 10; System.out.print(k + " "); } for (int k : arr) System.out.print(k + " "); What is printed as a result of executing the code segment? A 0 1 2 3 4 0 1 2 3 4 B 4 2 9 7 3 4 2 9 7 3 C 10 11 12 13 14 0 1 2 3 4 D 14 12 19 17 13 4 2 9 7 3 E 14 12 19 17 13 14 12 19 17 13
14 12 19 17 13 4 2 9 7 3
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? A 100 B 101 C 160 D 161 E 321
161
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? A 3 B 6 C 12 D 15 E 18
18
Consider the following method. public static int mystery(int value) { int sum = 0; int[] arr = {1, 4, 2, 5, 10, 3, 6, 4}; for (int item : arr) { if (item > value) { sum += item; } } return sum; } What value is returned as a result of the call mystery(4) ? A 6 B 15 C 21 D 29 E 35
21
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? A 1 B 2 C 3 D 5 E 6
5
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") ? A "4" B "53" C "531" D "543" E "54321"
53
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? A A B AA C AAA D AAAA E AAAAA
AA
Which of the following best describes the contents of numbers after the following statement has been executed? int m = mystery(n); A All values in positions 0 through m are less than n. B All values in positions m+1 through numbers.length-1 are less than n. C All values in positions m+1 through numbers.length-1 are greater than or equal to n. D The smallest value is at position m. E The largest value that is smaller than n is at position m.
All values in positions m+1 through numbers.length-1 are greater than or equal to n.
What is printed as a result of the call conditionalTest(3, -2)? A-A B-B C-C D-D E-Nothing is printed.
C
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 ? A Code segment 1 and code segment 2 will produce the same output. B Code segment 2 will print the sum of only the even integers from 1 through 30, inclusive because it starts sum at zero, increments k by twos, and terminates when k exceeds 30. 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. D Code segment 2 will print the sum of only the even integers from 1 through 60, inclusive because it starts sum at zero, increments k by twos, and iterates 30 times. E Code segment 2 will print the sum of only the odd integers from 1 through 60, inclusive because it starts k at one, increments k by twos, and iterates 30 times.
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.
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.println("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
Which of the following can be used to replace /* missing loop header */ so that the code segment works as intended? for (int j = 0; j < 3; j++) for (int j = 1; j < 3; j++) for (int j = 1; j <= 3; j++) A I only B II only C III only D I and II E I and III
I and III
Which of the following code segments could be used to replace /* body of updateAge */ so that the method will work as intended? I. int yrs = extraMonths % 12; int mos = extraMonths / 12; years = years + yrs; months = months + mos; II. int totalMonths = years * 12 + months + extraMonths; years = totalMonths / 12; months = totalMonths % 12; III. int totalMonths = months + extraMonths; years = years + totalMonths / 12; months = totalMonths % 12;
II and III only
Consider an integer array, nums, which has been declared and initialized with one or more integer values. Which of the following code segments updates nums so that each element contains the square of its original value? I. int k = 0; while (k < nums.length) { nums[k] = nums[k] * nums[k]; } II. for (int k = 0; k < nums.length; k++) { nums[k] = nums[k] * nums[k]; } III. for (int n : nums) { n = n * n; } A II only B I and II only C I and III only D II and III only E I, II, and III
II only
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? A Both code segments produce the same output, because they both iterate four times. B Both code segments produce the same output, because they both iterate five times. C Code segment I prints more values than code segment II does, because it iterates for one additional value of k. D Code segment II prints more values than code segment I, because it iterates for one additional value of k. 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.
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.
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? A The output of the code segment will be unchanged. B The string "Fun" will be printed more times because the outer loop will execute more times. C The string "Fun" will be printed more times because the inner loop will execute more times in each iteration of the outer loop. D The string "Fun" will be printed fewer times because the outer loop will execute fewer times. E The string "Fun" will be printed fewer times because the inner loop will execute fewer times in each iteration of the outer loop.
The string "Fun" will be printed more times because the outer loop will execute more times.
Which of the following best describes the value of s2 output by the method mystery ? A The sum of all positive values in arr B The sum of all positive even values in arr C The sum of all negative values in arr D The sum of all negative even values in arr E The sum of all negative odd values in arr
The sum of all negative values in arr
Which of the following best describes the value of s1 output by the method mystery ? A The sum of all positive values in arr B The sum of all positive even values in arr C The sum of all positive odd values in arr D The sum of all values greater than 2 in arr E The sum of all values less than 2 in arr
The sum of all positive even values in arr
Which of the following best explains why an incorrect value is printed? A The private variables hourlyRate and hoursWorked are not properly initialized. B The private variables hourlyRate and hoursWorked should have been declared public. C The private method calculateEarnings should have been declared public. D The variable earnings in the calculateEarnings method is a local variable. E The variables hourlyRate and hoursWorked in the calculateEarnings method are local variables.
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? A The class is missing an accessor method. B The instance variables name and number should be designated public instead of private. C The return type for the Info constructor is missing. D The variable name is not defined in the changeName method. E The variable num is not defined in the addNum method.
The variable num is not defined in the addNum method.
Consider the following code segment. if (false && true || false) { if (false || true && false) { System.out.print("First"); } else { System.out.print("Second"); } } if (true || true && false) { System.out.print("Third"); } What is printed as a result of executing the code segment? A First B Second C Third D FirstThird E SecondThird
Third
Consider the following code segment. Assume num is a properly declared and initialized int variable. if (num > 0) { if (num % 2 == 0) { System.out.println("A"); } else { System.out.println("B"); } } Which of the following best describes the result of executing the code segment? A When num is a negative odd integer, "B" is printed; otherwise, "A" is printed. B When num is a negative even integer, "B" is printed; otherwise, nothing is printed. C When num is a positive even integer, "A" is printed; otherwise, "B" is printed. D When num is a positive even integer, "A" is printed; when num is a positive odd integer, "B" is printed; otherwise, nothing is printed. E When num is a positive odd integer, "A" is printed; when num is a positive even integer, "B" is printed; otherwise, nothing is printed.
When num is a positive even integer, "A" is printed; when num is a positive odd integer, "B" is printed; otherwise, nothing is printed.
Assume obj1 and obj2 are object references. Which of the following best describes when the expression obj1 == obj2 is true? A When obj1 and obj2 are defined within the same method B When obj1 and obj2 are instances of the same class C When obj1 and obj2 refer to objects that contain the same data D When obj1 and obj2 refer to the same object E When obj1 and obj2 are private class variables defined in the same class
When obj1 and obj2 refer to the same object
Consider the following method. public static void message(int a, int b, int c) { if (a < 10) { if (b < 10) { System.out.print("X"); } System.out.print("Y"); } if (c < 10) { if (b > 10) { System.out.print("Y"); } else { System.out.print("Z"); } } } What is printed as a result of the call message(5, 15, 5) ? A XY B XYZ C Y D YY E Z
YY
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? A C B ci tm C eeStm D ncepC E eeSepC
eeSepC
`The twoInARow method below is intended to return true if any two consecutive elements of the parameter arr are equal in value and return false otherwise. public boolean twoInARow(int[] arr) { /* missing loop header */ { if (arr[k] == arr[k + 1]) { return true; } } return false; } Which of the following can be used to replace /* missing loop header */ so that the method will work as intended? A for (int k = 0; k < arr.length - 1; k++) B for (int k = 0; k < arr.length; k++) C for (int k = 1; k < arr.length; k++) D for (int k = arr.length - 1; k >= 0; k--) E for (int k = arr.length - 1; k > 0; k--)
for (int k = 0; k < arr.length - 1; k++)
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? A for (int k = 0; k < 7; k += 2) { System.out.print(k); } B for (int k = 0; k <= 7; k += 2) { System.out.print(k); } C for (int k = 0; k <= 8; k += 2) { System.out.print(k + 1); } D for (int k = 1; k < 7; k += 2) { System.out.print(k + 1); } E for (int k = 1; k <= 8; k += 2) { System.out.print(k); }
for (int k = 1; k <= 8; k += 2) { System.out.print(k); }
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_ ? A int inner = 0; inner < 3; inner++ B int inner = 1; inner < 3; inner++ C int inner = outer - 1; inner < 3; inner++ D int inner = outer; inner < 3; inner++ E int inner = outer + 1; inner < 3; inner++
int inner = outer; inner < 3; inner++
Consider the following instance variable and method. Assume that numbers has been initialized with the following values. {17, 34, 21, 42, 15, 69, 48, 25, 39} Which of the following represents the order of the values in numbers as a result of the call mystery(3)? A {17, 20, 21, 42, 45, 69, 48, 51, 39} B {17, 20, 23, 26, 29, 32, 35, 38, 41} C {17, 37, 21, 42, 18, 69, 48, 28, 39} D {20, 23, 21, 42, 45, 69, 51, 54, 39} E {20, 34, 21, 45, 15, 69, 51, 25, 39}
{17, 20, 21, 42, 45, 69, 48, 51, 39}
Consider the following code segment. boolean[] oldVals = {true, false, true, true}; boolean[] newVals = new boolean[4]; for (int j = oldVals.length - 1; j >= 0; j--) { newVals[j] = !(oldVals[j]); } What, if anything, will be the contents of newVals as a result of executing the code segment? A {true, true, false, true} B {true, false, true, true} C {false, true, false, false} D {false, false, true, false}
{false, true, false, false}
Consider the following code segment. 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? A 0 B 1 C 10 D 11 E 20
10
The classify method works as intended for some but not all values of the parameter volume. For which of the following values of volume would the correct value be returned when the classify method is executed? A 80 B 90 C 105 D 109 E 115
115
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 "a" will be printed fewer times because while each output line will have the same length as before, the number of lines printed will decrease by 1. B "a" will be printed more times because while the number of output lines will be the same as before, the length of each output line will increase by 1. 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. D "a" will be printed more times because both the number of output lines and the length of each line will increase by 1.
"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 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 ( a && b ) && ( !c && d ) B ( a || b ) && ( !c && d ) C ( a && b ) || ( c || !d ) D ( !a || !b ) && ( !c && d ) E !( a && b ) && ( c || !d )
( 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)
Assume that a, b, c, and d have been declared and initialized with int values. !((a >= b) && !(c < d)) Which of the following is equivalent to the expression above? A (a < b) || (c < d) B (a < b) || (c >= d) C (a < b) && (c < d) D (a >= b) || (c < d) E (a >= b) && (c < d)
(a < b) || (c < d)
For example, consider the following code segment. int[] arr = {11, 22, 100, 33, 100, 11, 44, 100}; System.out.println(findNext(arr, 100, 2)); The execution of the code segment should result in the value 4 being printed. Which of the following expressions could be used to replace /* condition */ so that findNext will work as intended? A (pos < arr.length) && (arr[pos] != val) B (arr[pos] != val) && (pos < arr.length) C (pos < arr.length) || (arr[pos] != val) D (arr[pos] == val) && (pos < arr.length) E (pos < arr.length) || (arr[pos] == val)
(pos < arr.length) && (arr[pos] != val)
The following code segment appears in a method in a class other than Class1 or Class2. Class1 c = new Class1(); c.init(); System.out.println(c.getVal()); What, if anything, is printed as a result of executing the code segment? A 2 B 1 C 0 D -2 E Nothing is printed because the code segment does not compile.
-2
What will be printed as a result of executing the code segment? A 0 2 2 3 3 0 B 0 7 2 5 3 3 C 0 7 2 5 5 10 D 1 7 3 5 4 3 E 7 2 5 3 3 0
0 7 2 5 3 3
Consider the following code segment. int x = 7; if (x < 7) { x = 2 * x; } if (x % 3 == 1) { x = x + 2; } System.out.print(3 * x); What is printed as a result of executing the code segment? A 7 B 9 C 14 D 21 E 27
27
Consider the following code segment. int[] arr = {3, 1, 0, 4, 2}; for(int j = 0; j < arr.length; j++) { System.out.print(arr[j] + j + " "); } What, if anything, is printed as a result of executing the code segment? A 3 1 0 4 2 B 3 2 2 7 6 C 6 2 0 8 4 D 7 2 3 6 2 E Nothing is printed, because an ArrayIndexOutOfBoundsException is thrown.
3 2 2 7 6
Assume that nums has been declared and initialized as an array of integer values. Which of the following best describes the value returned by the call mystery(nums) ? A The maximum value that occurs in nums B An index of the maximum value that occurs in nums C The number of times that the maximum value occurs in nums D A value that occurs most often in nums E An index of a value that occurs most often in nums
An index of a value that occurs most often in nums
Consider the following class definition. public class Element { public static int max_value = 0; private int value; public Element (int v) { value = v; if (value > max_value) { max_value = value; } } } The following code segment appears in a class other than Element. for (int i = 0; i < 5; i++) { int k = (int) (Math.random() * 10 + 1); if (k >= Element.max_value) { Element e = new Element(k); } } Which of the following best describes the behavior of the code segment? A Exactly 5 Element objects are created. B Exactly 10 Element objects are created. C Between 0 and 5 Element objects are created, and Element.max_value is increased only for the first object created. D Between 1 and 5 Element objects are created, and Element.max_value is increased for every object created. E Between 1 and 5 Element objects are created, and Element.max_value is increased for at least one object created.
Between 1 and 5 Element objects are created, and Element.max_value is increased for at least one object created.
The method countTarget below is intended to return the number of times the value target appears in the array arr. The method may not work as intended. public int countTarget(int[] arr, int target) { int count = 0; for (int j = 0; j <= arr.length; j++) // line 4 { if (arr[j] == target) { count++; } } return count; } Which of the following changes, if any, can be made to line 4 so that the method will work as intended? A Changing int j = 0; to int j = 1; B Changing j <= arr.length; to j < arr.length; C Changing j <= arr.length; to j < arr.length - 1; D Changing j <= arr.length; to j < arr.length + 1; E No change is necessary; the method works correctly as is.
Changing j <= arr.length; to j < arr.length;
Which of the following best describes the value of the Boolean expression shown below? a && !(b || a) A The value is always true. B The value is always false. C The value is true when a has the value false, and is false otherwise. D The value is true when b has the value false, and is false otherwise. E The value is true when either a or b has the value true, and is false otherwise.
The value is always false.
Which of the following code segments can replace /* missing code */ so the getCategory method works as intended? String cat;if (density > 3000){cat = "urban";}else if (density > 999){cat = "suburban";}else{cat = "rural";}return cat; String cat;if (density > 3000){cat = "urban";}if (density > 999) {cat = "suburban";}cat = "rural"; return cat; if (density > 3000){ return "urban";}if (density > 999) { return "suburban";}return "rural";
I and III only
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? A A WordClass object can change the value of the variable word more than once. B Every time a WordClass object is created, the max_word variable is referenced. C Every time a WordClass object is created, the value of the max_word variable changes. D No two WordClass objects can have their word length equal to the length of max_word. E The value of the max_word variable cannot be changed once it has been initialized.
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? A Expression I and expression II evaluate to different values for all values of A and B. B Expression I and expression II evaluate to the same value for all values of A and B. C Expression I and expression II evaluate to the same value only when A and B are the same. D Expression I and expression II evaluate to the same value only when A and B differ. E Expression I and expression II evaluate to the same value whenever A is true.
Expression I and expression II evaluate to the same value only when A and B differ.
Which of the code segments could be used to replace /* missing code */ so that compareTo can be used to order TemperatureReading objects by increasing temperature value? A II only B I and II only C I and III only D II and III only E I, II, and III
I and II only
Consider the following instance variable and incomplete method. The method calcTotal is intended to return the sum of all values in vals. private int[] vals; public int calcTotal() { int total = 0; /* missing code */ return total; } Which of the code segments shown below can be used to replace /* missing code */ so that calcTotal will work as intended? I. for (int pos = 0; pos < vals.length; pos++) { total += vals[pos]; } II. for (int pos = vals.length; pos > 0; pos--) { total += vals[pos]; } III. int pos = 0; while (pos < vals.length) { total += vals[pos]; pos++; }
I and III
Consider the following method. public String inRangeMessage(int value) { if (value < 0 || value > 100) return "Not in range"; else return "In range"; } Consider the following code segments that could be used to replace the body of inRangeMessage. I. if (value < 0) { if (value > 100) return "Not in range"; else return "In range"; } else return "In range"; II. if (value < 0) return "Not in range"; else if (value > 100) return "Not in range"; else return "In range"; III. if (value >= 0) return "In range"; else if (value <= 100) return "In range"; else return "Not in range"; Which of the replacements will have the same behavior as the original version of inRangeMessage ? A I only B II only C III only D I and III E II and III
II only
The price per box of ink pens advertised in an office supply catalog is based on the number of boxes ordered.The following table shows the pricing. The following incomplete method is intended to return the total cost of an order based on the value of the parameter numBoxes. Which of the following code segments can be used to replace /* missing code */ so that method getCost will work as intended? A I only B II only C III only D I and II E II and III
II only
Which of the following can be used to replace /* missing code */ so that isDecreasing will work as intended? for (int k = 0; k < nums.length; k++) { if (nums[k] <= nums[k + 1]) return false; } return true; for (int k = 1; k < nums.length; k++) { if (nums[k - 1] <= nums[k]) return false; } return true; for (int k = 0; k < nums.length - 1; k++) { if (nums[k] <= nums[k + 1]) return false; else return true; } return true; A I only B II only C III only D I and III E II and III
II only
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
Which of the following code segments could be used to replace /* body of someProcess */ so that the method will produce the results shown in the table? I. if ((n % 3 == 0) && (n % 4 == 0)) return n * 10; else return n; II. if ((n % 3 == 0) || (n % 4 == 0)) return n * 10; return n; III. if (n % 3 == 0) if (n % 4 == 0) return n * 10; return n;
II only
Consider the following code segment. int[] arr = {1, 2, 4, 0, 3}; for (int i : arr) { System.out.print(i); } Which of the following code segments will produce the same output as the code segment above?
III only
Consider the following method. public static void whatIsIt(int a, int b) { if ((a < b) && (a > 0)) { System.out.println("W"); } else if (a == b) { if (b > 0) { System.out.println("X"); } else if (b < 0) { System.out.println("Y"); } else if ((a == b) && (a == 0)) { System.out.println("Z"); } } } Which of the following method calls will cause "W" to be printed? whatIsIt(10, 10) whatIsIt(-5, 5) whatIsIt(7, 10) A I only B II only C III only D I and III E II and III
III only
`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
The method is intended to return an integer array sum such that for all k, sum [ k ] is equal to arr[0] + arr[1] + ... + arr[k]. For instance, if arr contains the values { 1, 4, 1, 3 }, the array sum will contain the values { 1, 5, 6, 9 }. The following two implementations of / * missing code * / are proposed so that partialSum will work as intended. Which of the following statements is true? A Both implementations work as intended, but implementation 1 is faster than implementation 2. B Both implementations work as intended, but implementation 2 is faster than implementation 1. C Both implementations work as intended and are equally fast. D Implementation 1 does not work as intended, because it will cause anArrayIndexOutOfBoundsException. E Implementation 2 does not work as intended, because it will cause anArrayIndexOutOfBoundsException.
Implementation 1 does not work as intended, because it will cause anArrayIndexOutOfBoundsException.
Consider the following method. public int someCode(int a, int b, int c) { if ((a < b) && (b < c)) return a; if ((a >= b) && (b >= c)) return b; if ((a == b) || (a == c) || (b == c)) return c; } Which of the following best describes why this method does not compile? A The reserved word return cannot be used in the body of an if statement. B It is possible to reach the end of the method without returning a value. C The if statements must have else parts when they contain return statements. D Methods cannot have multiple return statements. E The third if statement is not reachable.
It is possible to reach the end of the method without returning a value.
The method findLongest does not work as intended. Which of the following best describes the value returned by a call to findLongest ? A It is the length of the shortest consecutive block of the value target in nums. B It is the length of the array nums. C It is the number of occurrences of the value target in nums. D It is the length of the first consecutive block of the value target in nums. E It is the length of the last consecutive block of the value target in nums.
It is the number of occurrences of the value target in nums.
Consider the following class declaration. public class Circle { private double radius; public double computeArea() { private double pi = 3.14159; public double area = pi * radius * radius; return area; } // Constructor not shown. } Which of the following best explains why the computeArea method will cause a compilation error? A Local variables declared inside a method cannot be declared as public or private. B Local variables declared inside a method must all be private. C Local variables declared inside a method must all be public. D Local variables used inside a method must be declared at the end of the method. E Local variables used inside a method must be declared before the method header.
Local variables declared inside a method cannot be declared as public or private.
Consider the following method, which is intended to return the average (arithmetic mean) of the values in an integer array. Assume the array contains at least one element. public static double findAvg(double[] values) { double sum = 0.0; for (double val : values) { sum += val; } return sum / values.length; } Which of the following preconditions, if any, must be true about the array values so that the method works as intended? A The array values must be sorted in ascending order. B The array values must be sorted in descending order. C The array values must have only one mode. D The array values must not contain values whose sum is not 0. E No precondition is necessary; the method will always work as intended.
No precondition is necessary; the method will always work as intended.
Consider the following method. public static void addOneToEverything(int[] numbers) { for (int j = 0; j < numbers.length; j++) { numbers[j]++; } } Which of the following code segments, if any, can be used to replace the body of the method so that numbers will contain the same values? I. for (int num : numbers) { num++; } II. for (int num : numbers) { num[j]++; } III. for (int num : numbers) { numbers[num]++; } A I only B I and III only C II and III only D I, II, and III E None of the code segments will return an equivalent result.
None of the code segments will return an equivalent result.
Consider the following code segment, which traverses two integer arrays of equal length. If any element of arr1 is smaller than the corresponding (i.e., at the same index) element of minArray, the code segment should replace the element of minArray with the corresponding element of arr1. After the code segment executes, minArray should hold the smaller of the two elements originally found at the same indices in arr1 and minArray and arr1 should remain unchanged. for (int c = 0; c < arr1.length; c++) { if (arr1[c] < minArray[c]) { arr1[c] = minArray[c]; } else { minArray[c] = arr1[c]; } } Which of the following changes will ensure that the code segment always works as intended? A Changing the Boolean expression in line 1 to c <= arr1.length B Changing the relational operator in line 3 to > C Removing lines 5-8 D Swapping the positions of line 5 and line 9 E Removing lines 7-10
Removing lines 5-8
In the Toy class below, the raisePrice method is intended to increase the value of the instance variable price by the value of the parameter surcharge. The method does not work as intended. public class Toy { private String name; private double price; public Toy(String n, double p) { name = n; price = p; } public void raisePrice(double surcharge) // Line 12 { return price + surcharge; // Line 14 } Which of the following changes should be made so that the class definition compiles without error and the method raisePrice works as intended? A Replace line 14 with surcharge += price;. B Replace line 14 with price += surcharge;. C Replace line 14 with return price += surcharge;. D Replace line 12 with public raisePrice (double surcharge). E Replace line 12 with public double raisePrice (double surcharge).
Replace line 14 with price += surcharge;.
Consider the following incomplete method, which is intended to return the longest string in the string array words. Assume that the array contains at least one element. public static String longestWord(String[] words) { /* missing declaration and initialization */ for (int k = 1; k < words.length; k++) { if (words[k].length() > longest.length()) { longest = words[k]; } } return longest; } Which of the following can replace /* missing declaration and initialization */ so that the method will work as intended? A int longest = 0; B int longest = words[0].length(); C String longest = ""; D String longest = words[0]; E String longest = words[1];
String longest = words[0];
Which of the following code segments can be used to replace /* missing implementation */ so that findLastWord will work as intended? A int maxIndex = 0; for (int k = 0; k < words.length; k++) { if (words[k].compareTo(maxIndex) > 0) { maxIndex = k; } } return words[maxIndex]; B int maxIndex = 0; for (int k = 1; k <= words.length; k++) { if (words[k].compareTo(words[maxIndex]) > 0) { maxIndex = k; } } return words[maxIndex]; C int maxIndex = 0; for (int k = 1; k < words.length; k++) { if (words[k].compareTo(words[maxIndex]) > 0) { maxIndex = k; } } return maxIndex; D String maxWord = words[0]; for (int k = 1; k < words.length; k++) { if (words[k].compareTo(maxWord) > 0) { maxWord = k; } } return maxWord; E String maxWord = words[0]; for (int k = 1; k < words.length; k++) { if (words[k].compareTo(maxWord) > 0) { maxWord = words[k]; } } return maxWord;
String maxWord = words[0]; for (int k = 1; k < words.length; k++) { if (words[k].compareTo(maxWord) > 0) { maxWord = words[k]; } } return maxWord;
String[] animals = {"horse", "cow", "goat", "dog", "cat", "mouse"}; int count = 0; for (int i = 0; i <= animals.length; i++) { if (animals[i].indexOf(str) >= 0) { count++; } } System.out.println(count); The code segment does not work as intended. Which of the following changes should be made so the code segment works as intended? A The Boolean expression in the for loop header should be changed to i < animals.length. B The Boolean expression in the for loop header should be changed to i < animals.length - 1. C The Boolean expression in the for loop header should be changed to i < animals[i].length. D The condition in the if statement should be changed to animals[i].equals(str). E The condition in the if statement should be changed to animals[i].substring(str).
The Boolean expression in the for loop header should be changed to i < animals.length.
Consider the following code segment, which is intended to print the sum of all elements of an array. int[] arr = {10, 5, 1, 20, 6, 25}; int sum = 0; for (int k = 0; k <= arr.length; k++) { sum += arr[k]; } System.out.println("The sum is " + sum); A runtime error occurs when the code segment is executed. Which of the following changes should be made so that the code segment works as intended? A The for loop header should be replaced with for (int k = 0; k < arr.length; k++). B The for loop header should be replaced with for (int k = 0; k <= arr.length; k--). C The for loop header should be replaced with for (int k = 1; k <= arr.length - 1; k++). D The statement in the body of the for loop should be replaced with sum += arr[0]. E The statement in the body of the for loop should be replaced with sum += arr[k - 1].
The for loop header should be replaced with for (int k = 0; k < arr.length; k++).
Which of the following best describes the problem with the given implementation of the shuffle method? A Executing shuffle may cause an ArrayIndexOutOfBoundsException. B The first element of the returned array (result [0] ) may not have the correct value. C The last element of the returned array (result [result.length − 1] ) may not have the correct value. D One or more of nums [0] ... nums [nums.length / 2 − 1] may have been copied to the wrong position(s) in the returned array. E One or more of nums [nums.length / 2] ... nums[nums.length − 1] may have been copied to the wrong position(s) in the returned array.
The last element of the returned array (result [result.length − 1] ) may not have the correct value.
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? A The method call will print fewer characters than it did before the change because the loop will iterate fewer times. B The method call will print more characters than it did before the change because the loop will iterate more times. 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. D 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 8 in a string whose last element is at index 7. E The behavior of the code segment will remain unchanged.
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 method. public String exercise(int input) { if (input < 10) { return "alpha"; } if (input < 5) { return "beta"; } if (input < 1) { return "gamma"; } return "delta"; } Assume that the int variable x has been initialized in another method in the same class. Which of the following describes the conditions under which the method call exercise(x) will return "gamma" ? A The method will never return "gamma". B The method will return "gamma" if x is less than 1. C The method will return "gamma" if x is between 1 and 4, inclusive. D The method will return "gamma" if x is between 5 and 9, inclusive. E The method will always return "gamma".
The method will never return "gamma".
Consider the following statement. boolean x = (5 < 8) == (5 == 8); What is the value of x after the statement has been executed? A 3 B 5 C 8 D true E false
false
Consider the following class definition. public class Password { private String password; public Password (String pwd) { password = pwd; } public void reset(String new_pwd) { password = new_pwd; } } Consider the following code segment, which appears in a method in a class other than Password. The code segment does not compile. Password p = new Password("password"); System.out.println("The new password is " + p.reset("password")); Which of the following best identifies the reason the code segment does not compile? A The code segment attempts to access the private variable password from outside the Password class. B The new password cannot be the same as the old password. C The Password class constructor is invoked incorrectly. D The reset method cannot be called from outside the Password class. E The reset method does not return a value that can be printed.
The reset method does not return a value that can be printed.
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? A The two code segments prin
The two code segments print the same value only when grade is below 80.
Consider the following class definition. public class ItemInventory { private int numItems; public ItemInventory(int num) { numItems = num; } public updateItems(int newNum) { numItems = newNum; } } Which of the following best identifies the reason the class does not compile? A The constructor header is missing a return type. B The updateItems method is missing a return type. C The constructor should not have a parameter. D The updateItems method should not have a parameter. E The instance variable numItems should be public instead of private.
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; ? A There will be one more value printed because the outer loop will iterate one additional time. B There will be four more values printed because the outer loop will iterate one additional time. C There will be one less value printed because the outer loop will iterate one fewer time. D There will be four fewer values printed because the outer loop will iterate one fewer time. E There will be no change to the output of the code segment.
There will be four more values printed because the outer loop will iterate one additional time.
Consider the following code segment. What is printed as a result of executing the code segment? A Value is: 21 B Value is: 2.3333333 C Value is: 2 D Value is: 0 E Value is: 1
Value is: 2
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 ? A Always B Never C When a and b have the same value D When a has the value false E When b has the value false
When b has the value false
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? A aaaXXX555 B aaaXXX C XXX555 D 555 E aaa
aaaXXX
Assume that x and y are boolean variables and have been properly initialized. Which of the following best describes the result of evaluating the expression above? A true always B false always C true only when x is true and y is true D true only when x and y have the same value E true only when x and y have different values
false always
Consider the following class, which uses the instance variable balance to represent a bank account balance. public class BankAccount { private double balance; public double deposit(double amount) { /* missing code */ } } The deposit method is intended to increase the account balance by the deposit amount and then return the updated balance. Which of the following code segments should replace /* missing code */ so that the deposit method will work as intended? A amount = balance + amount; return amount; B balance = amount; return amount; C balance = amount; return balance; D balance = balance + amount; return amount; E balance = balance + amount; return balance;
balance = balance + amount; return balance;
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? A biggest always returns the value of a. B biggest may not work correctly when c has the greatest value. C biggest may not work correctly when a and b have equal values. D biggest may not work correctly when a and c have equal values. E biggest may not work correctly when b and c have equal values.
biggest may not work correctly when a and b have equal values.
Which of the following statements assigns the same value to b2 as the code segment assigns to b1 for all values of num ? A boolean b2 = (num > -100) && (num < 100); B boolean b2 = (num > -100) || (num < 100); C boolean b2 = (num < -100) || (num > 100); D boolean b2 = (num < -100) && (num > 0 || num < 100); E boolean b2 = (num < -100) || (num > 0 && num < 100);
boolean b2 = (num < -100) || (num > 0 && num < 100);
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 ? A boolean b2 = false || (17 % 3 == 2); B boolean b2 = false && (17 % 3 == 2); C boolean b2 = true || (17 % 3 == 1); D boolean b2 = (true || false) && true; E boolean b2 = (true && false) || true;
boolean b2 = false && (17 % 3 == 2);
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? A choice < 5 B choice >= 5 and choice <= 10 C choice > 10 D choice == 5 or choice == 10 E There is no value for choice that will cause the two code segments to produce different output.
choice > 10
A school that does not have air conditioning has published a policy to close school when the outside temperature reaches or exceeds 95°F. The following code segment is intended to print a message indicating whether or not the school is open, based on the temperature. Assume that the variable degrees has been properly declared and initialized with the outside temperature. if (degrees > 95) { System.out.println("School will be closed due to extreme heat"); } else { System.out.println("School is open"); } Which of the following initializations for degrees, if any, will demonstrate that the code segment may not work as intended? A degrees = 90; B degrees = 94; C degrees = 95; D degrees = 96; E The code will work as intended for all values of degrees.
degrees = 95;
Which of the following code segments can be used to replace /* missing code */ so that diff will work as intended? A if (pred[i] < act[i]) { num = act[i] - pred[i]; } B if (pred[i] > act[i]) { num = pred[i] - act[i]; } C if (pred[i] - act[i] > num) { num = pred[i] - act[i]; } D if (Math.abs(pred[i] - act[i]) < num) { num = Math.abs(pred[i] - act[i]); } E if (Math.abs(pred[i] - act[i]) > num) { num = Math.abs(pred[i] - act[i]); }
if (Math.abs(pred[i] - act[i]) > num) { num = Math.abs(pred[i] - act[i]); }
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 ? A if (a < b && c != d) { System.out.println("dog"); } else { System.out.println("cat"); } B if (a < b && c != d) { System.out.println("cat"); } else { System.out.println("dog"); } C if (a > b && c == d) { System.out.println("cat"); } else { System.out.println("dog"); } D if (a >= b || c == d) { System.out.println("cat"); } else { System.out.println("dog"); } E if (a >= b && c == d) { System.out.println("cat"); } else { System.out.println("dog"); }
if (a >= b && c == d) { System.out.println("cat"); } else { System.out.println("dog"); }
The following code segment is intended to store in maxPages the greatest number of pages found in any Book object in the array bookArr. Book[] bookArr = { /* initial values not shown */ }; int maxPages = bookArr[0].getPages(); for (Book b : bookArr) { /* missing code */ } Which of the following can replace /* missing code */ so the code segment works as intended? A if (b.pages > maxPages) { maxPages = b.pages; } B if (b.getPages() > maxPages) { maxPages = b.getPages(); } C if (Book[b].pages > maxPages) { maxPages = Book[b].pages; } D if (bookArr[b].pages > maxPages) { maxPages = bookArr[b].pages; } E if (bookArr[b].getPages() > maxPages) { maxPages = bookArr[b].getPages(); }
if (b.getPages() > maxPages) { maxPages = b.getPages(); }
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? A int j = 1; while (j < 10) { j += 2; System.out.print(j); } B int j = 1; while (j < 10) { System.out.print(j); j += 2; } C int j = 1; while (j <= 10) { j += 2; System.out.print(j); } D int j = 1; while (j >= 10) { j += 2; System.out.print(j); } E int j = 1; while (j >= 10) { System.out.print(j); j += 2; }
int j = 1; while (j < 10) { System.out.print(j); j += 2; }
Assume that an array of integer values has been declared as follows and has been initialized. int[] arr = new int[10]; Which of the following code segments correctly interchanges the value of arr[0] and arr[5] ? A arr[0] = 5; arr[5] = 0; B arr[0] = arr[5]; arr[5] = arr[0]; C int k = arr[5]; arr[0] = arr[5]; arr[5] = k; D int k = arr[0]; arr[0] = arr[5]; arr[5] = k; E int k = arr[5]; arr[5] = arr[0]; arr[0] = arr[5];
int k = arr[0]; arr[0] = arr[5]; arr[5] = k;
Consider the code segment below, where arr is a one-dimensional array of integers. int sum = 0; for (int n : arr) { sum = sum + 2 * n; } System.out.print(sum); Which of the following code segments will produce the same output as the code segment above? A int sum = 0; for (int k = 0; k < arr.length; k++) { sum = sum + 2 * k; } System.out.print(sum); B int sum = 0; for (int k = 0; k <= arr.length; k++) { sum = sum + 2 * k; } System.out.print(sum); C int sum = 0; for (int k = 1; k <= arr.length; k++) { sum = sum + 2 * k; } System.out.print(sum); D int sum = 0; for (int k = 0; k < arr.length; k++) { sum = sum + 2 * arr[k]; } System.out.print(sum); E int sum = arr[0]; for (int k = 1; k <= arr.length; k++) { sum = sum + 2 * arr[k]; } System.out.print(sum);
int sum = 0; for (int k = 0; k < arr.length; k++) { sum = sum + 2 * arr[k]; } System.out.print(sum);
Consider the following method. public static int getValue(int[] data, int j, int k) { return data[j] + data[k]; } Which of the following code segments, when appearing in another method in the same class as getValue, will print the value 70 ? A int arr = {40, 30, 20, 10, 0}; System.out.println(getValue(arr, 1, 2)); B int[] arr = {40, 30, 20, 10, 0}; System.out.println(getValue(arr, 1, 2)); C int[] arr = {50, 40, 30, 20, 10}; System.out.println(getValue(arr, 1, 2)); D int arr = {40, 30, 20, 10, 0}; System.out.println(getValue(arr, 2, 1)); E int arr = {50, 40, 30, 20, 10}; System.out.println(getValue(arr, 2, 1));
int[] arr = {50, 40, 30, 20, 10}; System.out.println(getValue(arr, 1, 2));
Consider the following method. public int[] addNum(int[] array, int first, int second, int num) { int[] newArray = new int[array.length]; newArray[first] = array[first] + num; newArray[second] = array[second] + num; return newArray; } Which of the following code segments, appearing in the same class as the addNum method, will result in array2 having the contents {0, 0, 13, 0, 9, 0, 0} ? A int[] array1 = {5, 2, 8, 6, 4, 3, 9}; int[] array2 = addNum(array1, 2, 4, 5); B int[] array1 = {-5, -5, 13, 0, 9, 0, 0}; int[] array2 = addNum(array1, 2, 4, 5); C int[] array1 = {5, 2, 8, 6, 4, 3, 9}; int[] array2 = addNum(array1, 3, 5, 5); D int[] array1 = {5, 8, 2, 4, 6, 3, 9}; int[] array2 = addNum(array1, 2, 4, 5); E int[] array1 = {0, -5, 8, 0, 9, 0, 0}; int[] array2 = addNum(array1, 2, 4, 5);
int[] array1 = {5, 2, 8, 6, 4, 3, 9}; int[] array2 = addNum(array1, 2, 4, 5);
The following method is intended to return true if and only if the parameter val is a multiple of 4 but is not a multiple of 100 unless it is also a multiple of 400. The method does not always work correctly. public boolean isLeapYear(int val) { if ((val % 4) == 0) { return true; } else { return (val % 400) == 0; } } Which of the following method calls will return an incorrect response? A isLeapYear(1900) B isLeapYear(1984) C isLeapYear(2000) D isLeapYear(2001) E isLeapYear(2010)
isLeapYear(1900)
Consider the following method, which is intended to return an array of integers that contains the elements of the parameter arr arranged in reverse order. For example, if arr contains {7, 2, 3, -5}, then a new array containing {-5, 3, 2, 7} should be returned and the parameter arr should be left unchanged. public static int[] reverse(int[] arr) { int[] newArr = new int[arr.length]; for (int k = 0; k < arr.length; k++) { /* missing statement */ } return newArr; } Which of the following statements can be used to replace /* missing statement */ so that the method works as intended? A newArray[k] = arr[-k]; B newArray[k] = arr[k - arr.length]; C newArray[k] = arr[k - arr.length - 1]; D newArray[k] = arr[arr.length - k]; E newArray[k] = arr[arr.length - k - 1];
newArray[k] = arr[arr.length - k - 1];
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? A count != 0 B count > 0 C num >= 0 D num != 0 E num == 0
num != 0
The following incomplete method is intended to return the largest integer in the array numbers. Which of the following can be used to replace /* condition */ and /* statement */ so that findMax will work as intended? A /* condition */ /* statement */numbers[index] > numbers[posOfMax] posOfMax = numbers[index]; B /* condition */ /* statement */numbers[index] > numbers[posOfMax] posOfMax = index; C /* condition */ /* statement */numbers[index] > posOfMax posOfMax = numbers[index]; D /* condition */ /* statement */numbers[index] < posOfMax posOfMax = numbers[index]; E /* condition */ /* statement */numbers[index] < numbers[posOfMax] posOfMax = index;
numbers[index] > numbers[posOfMax] posOfMax = index;
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? A one dot equals two B one dot equals two one dot equals three C one dot equals three two equals equals three D one dot equals two one dot equals three two equals equals three E Nothing is printed.
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? A public String make; public String model; public Car(String myMake, String myModel) { /* implementation not shown */ } B public String make; public String model; private Car(String myMake, String myModel) { /* implementation not shown */ } C private String make; private String model; public Car(String myMake, String myModel) { /* implementation not shown */ } D public String make; private String model; private Car(String myMake, String myModel) ( /* implementation not shown */ } E private String make; private String model; private Car(String myMake, String myModel) { /* implementation not shown */ }
private String make; private String model; public Car(String myMake, String myModel) { /* implementation not shown */ }
Consider the following code segment. int a = 10; int b = 5 * 2; System.out.print(a == b); What is printed as a result of executing the code segment? A 5 B 10 C 10 == 10 D true E false
true
The calculateFee method is intended to calculate the total fee for renting a car. The total fee is equal to the number of days of the rental, days, times the daily rental rate plus the number of miles driven, miles, times the per mile rate. Which of the following code segments should replace /* missing code */ so that the calculateFee method will work as intended? A return dailyRate + mileageRate; B return (daily * dailyRate) + (mileage * mileageRate); C return (daily * days) + (mileage * miles); D return (days * dailyRate) + (miles * mileageRate); E return (days + miles) * (dailyRate + mileageRate);
return (days * dailyRate) + (miles * mileageRate);
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? A return (x <= lower) && (x >= upper); B return (x <= lower) || (x >= upper); C return lower <= x <= upper; D return (x >= lower) && (x <= upper); E return (x >= lower) || (x <= upper);
return (x >= lower) && (x <= upper);
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? A return (d1 - d2) <= tolerance; B return ((d1 + d2) / 2) <= tolerance; C return (d1 - d2) >= tolerance; D return ( (d1 + d2) / 2) >= tolerance; E return Math.abs(d1 - d2) <= tolerance;
return Math.abs(d1 - d2) <= tolerance;
Consider the following methods. When the call test ( ) is executed, what are the values of s and n at the point indicated by / * End of method * / ? A s / n world / 6 B s / n worldpeace / 6 C s / n world / 12 D s / n worldpeace / 12 E s / n peace / 12
s / n world / 6
Which of the following statements should be used to replace / * missing code * / so that sumArraywill work as intended? A sum = key [ i ] ; B sum += key [i - 1] ; C sum += key [ i ] ; D sum += sum + key[i - 1] ; E sum += sum + key [ i ] ;
sum += key [i - 1] ;