CSA midterm

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

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

E I, II, and III

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

A x

Consider the following method. 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

C 7

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

C 8, 9, 11

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 ? A B C D E

A

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 ( a && b ) && ( !c && d )

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 (a < b) || (c < d)

Consider the following incomplete method. Method findNext is intended to return the index of the first occurrence of the value val beyond the position start in array arr. // returns index of first occurrence of val in arr // after position start; // returns arr.length if val is not found public int findNext(int[] arr, int val, int start) { int pos = start + 1; while ( /* condition */ ) pos++; return pos; } 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 < ar

A (pos < arr.length) && (arr[pos] != val)

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)

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

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

A I 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

A II 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

A Integer.MAX_VALUE

In the following code segment, assume that the string str has been properly declared and initialized. The code segment is intended to print the number of strings in the array animals that have str as a substring. 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 stat

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

A The for loop header should be replaced with for (int k = 0; k < arr.length; k++).

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

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

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

A always true

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

A for (int k = 0; k < arr.length - 1; k++)

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

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

A isLeapYear(1900)

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

A one dot equals two

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

C 10

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 segme

A randomNumber = 0.70;

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

A s / n world / 6

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

C 21

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"

B "53"

Consider the following code segment. 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

B 0 7 2 5 3 3

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

B 3 2 2 7 6

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

B 6

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

B AA

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.

B Changing j <= arr.length; to j < arr.length;

Consider the following class definition. public class WordClass { private final String word; private static String max_word = ""; public WordClass (String s) { word = s; if (word.length() > max_word.length()) { max_word = word; } } } Which of the following is a true statement about the behavior of WordClass objects? A A WordClass object can change the value of the variable word more than once. B Every time a WordClass object is created, the max_word variable is referenced. C Every time a WordClass object is created, the value of the max_word variable changes. D No two WordClass objects can have their word length equal to the length of max_word. E The value of the max_word variable cannot be changed once it has been initialized.

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

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 A I only B II only C III only D I and II E II and III

B II only

Consider the following incomplete method. public int someProcess(int n) { /* body of someProcess */ } The following table shows several examples of input values and the results that should be produced by calling someProcess. Input Valuen Value Returned bysomeProcess(n) 33066077880990111112120141416160 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; A I only B II only C III only D I and III E II and III

B II only

Consider the following method that is intended to return true if an array of integers is arranged in decreasing order and return false otherwise. /** @param nums an array of integers * @return true if the values in the array appear in decreasing order * false otherwise */ public static boolean isDecreasing(int[] nums) { /* missing code */ } 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

B 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

B 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? I. int[] arr = {1, 2, 4, 0, 3}; for (int i : arr) { System.out.print(arr[i]); } II. int[] arr = {1, 2, 4, 0, 3}; for (int i = 0; i < arr.length; i++) { System.out.print(i); } III. int[] arr = {1, 2, 4, 0, 3}; for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]); } A I only B III only C I and II only D I and III only E I, II, and III

B III only

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.

B It is possible to reach the end of the method without returning a value.

In the Toy class below, the raisePrice method is intended to increase the value of the instance variable price by the value of the parameter surcharge. The method does not work as intended. public class Toy { private String name; private double price; public Toy(String n, double p) { name = n; price = p; } public void raisePrice(double surcharge) // Line 12 { return price + surcharge; // Line 14 } Which of the following changes should be made so that the class definition compiles without error and the method raisePrice works as intended? A Replace line 14 with surcharge += price;. B Replace line 14 with price += surcharge;. C Replace line 14 with return price += surcharge;. D Replace line 12 with public raisePrice (double surcharge). E Replace line 12 with public double raisePrice (double surcharge).

B Replace line 14 with price += surcharge;.

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

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

Consider the following class definition. public class ItemInventory { private int numItems; public ItemInventory(int num) { numItems = num; } public updateItems(int newNum) { numItems = newNum; } } Which of the following best identifies the reason the class does not compile? A The constructor header is missing a return type. B The updateItems method is missing a return type. C The constructor should not have a parameter. D The updateItems method should not have a parameter. E The instance variable numItems should be public instead of private.

B The updateItems method is missing a return type.

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.

B The value is always false.

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.

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

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

B aaaXXX

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;

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

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

B false always

Consider the following class definition. public class Book { private int pages; public int getPages() { return pages; } // There may be instance variables, constructors, and methods not shown. } 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(); }

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

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

Consider the following method that is intended to return the sum of the elements in the array key. 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 ] ;

B sum += key [i - 1] ;

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)

B valueOne == valueTwo

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)

B while (k < 4)

Consider the following code segment. for (int x = 0; x <= 4; x++) // Line 1 { for (int y = 0; y < 4; y++) // Line 3 { System.out.print("a"); } System.out.println(); } Which of the following best explains the effect of simultaneously changing x <= 4 to x < 4 in line 1 and y < 4 to y <= 4 in line 3 ? 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. E The output of the code segment will not change in an

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.

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;

C /* expression *//* loop body */true if ((arr[k] % 2) != 0) isEven = false;

Consider the following instance variable and method. 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.

C All values in positions m+1 through numbers.length-1 are greater than or equal to n.

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? A A B B C C D D E Nothing is printed.

C C

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)? A A B B C C D D E Nothing is printed.

C C

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

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

Consider the following instance variable nums and method findLongest with line numbers added for reference. Method findLongest is intended to find the longest consecutive block of the value target occurring in the array nums; however, findLongest does not work as intended.For example, if the array nums contains the values [7, 10, 10, 15, 15, 15, 15, 10,10, 10, 15, 10, 10], the call findLongest (10) should return 3, the length of the longest consecutive block of 10s. 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

C It is the number of occurrences of the value target in nums.

Consider the following class definition. public class Something { private static int count = 0; public Something() { count += 5; } public static void increment() { count++; } } The following code segment appears in a method in a class other than Something. Something s = new Something(); Something.increment(); Which of the following best describes the behavior of the code segment? A The code segment does not compile because the increment method should be called on an object of the class Something, not on the class itself. B The code segment creates a Something object s. The class Something's static variable count is initially 0, then increased by 1. C The code segment creates a Something object s. The class Something's static variable count is initially 0, then increased by 5, then increased by 1. D The code segment creates a Something object s. After executing the code segment, the object s has a count value of

C The code segment creates a Something object s. The class Something's static variable count is initially 0, then increased by 5, then increased by 1.

Consider the following instance variable and method. 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.

C The largest value in arr is negative.

Consider a shuffle method that is intended to return a new array that contains all the elements from nums, but in a different order. Let n be the number of elements in nums. The shuffle method should alternate the elements from nums [0] ... nums[n / 2 - 1] with the elements from nums[n / 2] ...nums[n - 1], as illustrated in the following examples. The following implementation of the shuffle method does not work as intended. 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 o

C The last element of the returned array (result [result.length − 1] ) may not have the correct value.

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

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.

The question refer to the following data field and method. private int[] arr; // precondition: arr.length > 0public void mystery() { int sl = 0; int s2 = 0; for (int k = 0; k < arr.length; k++) { int num = arr[k]; if ((num > 0) && (num % 2 == 0)) sl += num; else if (num < 0) s2 += num; } System.out.println(s1); System.out.println(s2); } 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

C The sum of all negative values in arr

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

C Third

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

C Value is: 2

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

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

C a == b

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.

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

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

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

C degrees = 95;

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

C int[] arr = {50, 40, 30, 20, 10}; System.out.println(getValue(arr, 1, 2));

The Car class will contain two string attributes for a car's make and model. The class will also contain a constructor. public class Car { /* missing code */ } Which of the following replacements for /* missing code */ is the most appropriate implementation of the class? A public String make; public String model; public Car(String myMake, String myModel) { /* implementation not shown */ } B public String make; public String model; private Car(String myMake, String myModel) { /* implementation not shown */ } C private String make; private String model; public Car(String myMake, String myModel) { /* implementation not shown */ } D public String make; private String model; private Car(String myMake, String myModel) ( /* implementation not shown */ } E private String make; private String model; private Car(String myMake, String myModel) { /* implementation not shown */ }

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

public class Point { private double myX; private double myyY; // postcondition: this Point has coordinates (0,0) public Point () { /* implementation not shown */ } // postcondition: this Point has coordinates (x,y) public Point(double x, double y) { /* implementation not shown */ } // other methods not shown } public class Circle { private Point myCenter; private double myRadius; // postcondition: this Circle has center at (0, 0) and radius 0.0 public Circle() { /* implementation not shown */ } // postcondition: this Circle has the given center and radius public Circle(Point center, double radius) { /* implementation not shown */ } // other methods not shown } 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 isIn

C public boolean isInside(Point p)

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;

C weight += aw;

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

C x = 10 and y = 30

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}

C {1, 1, 3, 3, 5, 5, 7}

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}

C {1, 2, 3, 5, 6, 7, 7}

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

D When obj1 and obj2 refer to the same object

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)true​compareThree(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)

D (x > y) == (y > z)

Consider the following class definitions. public class Class1 { private int val1; public Class1() { val1 = 1; } public void init () { Class2 c2 = new Class2(); c2.init(this, val1); } public void update(int x) { val1 -= x; } public int getVal() { return val1; } } public class Class2 { private int val2; public Class2() { val2 = 2; } public void init(Class1 c, int y) { c.update(val2 + y); } } The following code segment appears in a method in a class other than Class1 or Class2. Class1 c = new Class1(); c.init(); System.out.println(c.getVal()); What, if anything, is printed as a result of executing the code segment? A 2 B 1 C 0 D -2 E Nothing is printed because the code segment does not compile.

D -2

Consider the following class definition. public class SomeClass { private int x = 0; private static int y = 0; public SomeClass(int pX) { x = pX; y++; } public void incrementY() { y++; } public void incrementY(int inc) { y += inc; } public int getY() { return y; } } 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

D 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

D 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

D 161

Consider the following method, which returns an int based on its parameter x. public static int puzzle(int x) { if (x > 20) { x -= 2; } else if (x % 2 == 0) // Line 7 { x += 4; } return x; } 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

D 22

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

D 60

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

D 75.0

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.

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

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.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"); } A I only B II only C III only D I and II only E I, II, and III

D 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++; } A I only B II only C III only D I and III E II and III

D I and III

The following categories are used by some researchers to categorize zip codes as urban, suburban, or rural based on population density. An urban zip code is a zip code with more than 3,000 people per square mile. A suburban zip code is a zip code with between 1,000 and 3,000 people, inclusive, per square mile. A rural zip code is a zip code with fewer than 1,000 people per square mile. Consider the following method, which is intended to categorize a zip code as urban, suburban, or rural based on the population density of the area included in the zip code. public static String getCategory(int density) { /* missing code */ } 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) {

D I and III only

Consider the following instance variables and incomplete method that are part of a class that represents an item. The variables years and months are used to represent the age of the item, and the value for months is always between 0 and 11, inclusive. Method updateAge is used to update these variables based on the parameter extraMonths that represents the number of months to be added to the age. private int years; private int months; // 0 <= months <= 11 // precondition: extraMonths >= 0 public void updateAge(int extraMonths) { /* body of updateAge */ } 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 = mo

D II and III only

Consider the following instance variable, arr, and incomplete method, partialSum. 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 anArrayIndexOutOfBoundsExcept

D Implementation 1 does not work as intended, because it will cause anArrayIndexOutOfBoundsException.

Consider the following instance variable and method. 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

D Returns the index of the largest value in array array

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

D String longest = words[0];

The class Worker is defined below. The class includes the method getEarnings, which is intended to return the total amount earned by the worker. public class Worker { private double hourlyRate; private double hoursWorked; private double earnings; public Worker(double rate, double hours) { hourlyRate = rate; hoursWorked = hours; } private void calculateEarnings() { double earnings = 0.0; earnings += hourlyRate * hoursWorked; } public double getEarnings() { calculateEarnings(); return earnings; } } The following code segment appears in a method in a class other than Worker. The code segment is intended to print the value 800.0, but instead prints a different value because of an error in the Worker class. Worker bob = new Worker(20.0, 40.0); System.out.println(bob.getEarnings()); Which of the following best explains why an incorrect value is printed? A The private variables hourlyRate and hoursWorked are not properly

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

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.

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.

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

D YY

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

D int sum = 0; for (int k = 0; k < arr.length; k++) { sum = sum + 2 * arr[k]; } System.out.print(sum);

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

D num != 0

Consider the following class definition. public class RentalCar { private double dailyRate; // the fee per rental day private double mileageRate; // the fee per mile driven public RentalCar(double daily, double mileage) { dailyRate = daily; mileageRate = mileage; } public double calculateFee(int days, int miles) { /* missing code */ } } The calculateFee method is intended to calculate the total fee for renting a car. The total fee is equal to the number of days of the rental, days, times the daily rental rate plus the number of miles driven, miles, times the per mile rate. Which of the following code segments should replace /* missing code */ so that the calculateFee method will work as intended? 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) * (dailyRa

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

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

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

D true

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

D true false true

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)

D while (r <= 101)

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

D x = 4 y = -1

Vehicles are classified based on their total interior volume. The classify method is intended to return a vehicle classification String value based on total interior volume, in cubic feet, as shown in the table below. Vehicle size classTotal interior volumeMinicompactLess than 85 cubic feetSubcompact85 to 99 cubic feetCompact100 to 109 cubic feetMid-Size110 to 119 cubic feetLarge120 cubic feet or more The classify method, which does not work as intended, is shown below. public static String classify(int volume) { String carClass = ""; if (volume >= 120) { carClass = "Large"; } else if (volume < 120) { carClass = "Mid-Size"; } else if (volume < 110) { carClass = "Compact"; } else if (volume < 100) { carClass = "Subcompact"; } else { carClass = "Minicompact"; } return carClass; } The classify method works as intended for some but not all values of the parameter volume. For which of the following values of volume woul

E 115

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

E 18

Consider the following method. 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

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

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

Consider the following code segment. /* missing loop header */ { for (int k = 0; k < 4; k++) { System.out.print(k); } System.out.println(); } The code segment is intended to produce the following output. 0123 0123 0123 Which of the following can be used to replace /* missing loop header */ so that the code segment works as intended? 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

E I 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

E II and III

Consider the following incomplete method that is intended to return a string formed by concatenating elements from the parameter words. The elements to be concatenated start with startIndex and continue through the last element of words and should appear in reverse order in the resulting string. For example, the following code segment uses a call to the concatWords method. 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

E II and III

Consider the following instance variable nums and method findLongest with line numbers added for reference. Method findLongest is intended to find the longest consecutive block of the value target occurring in the array nums; however, findLongest does not work as intended.For example, if the array nums contains the values [7, 10, 10, 15, 15, 15, 15, 10,10, 10, 15, 10, 10], the call findLongest (10) should return 3, the length of the longest consecutive block of 10s. 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.

E Insert the statement lenCount = 0; between lines 12 and 13.

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.

E None of the code segments will return an equivalent result.

Consider the following instance variable and incomplete method. The method is intended to return a string from the array words that would be last alphabetically. private String[] words; public String findLastWord() { /* missing implementation */ } Assume that words has been initialized with one or more strings containing only lowercase letters. 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 max

E String maxWord = words[0]; for (int k = 1; k < words.length; k++) { if (words[k].compareTo(maxWord) > 0) { maxWord = words[k]; } } return maxWord;

Consider the following class definition. public class Info { private String name; private int number; public Info(String n, int num) { name = n; number = num; } public void changeName(String newName) { name = newName; } public int addNum(int n) { num += n; return num; } } Which of the following best explains why the class will not compile? A The class is missing an accessor method. B The instance variables name and number should be designated public instead of private. C The return type for the Info constructor is missing. D The variable name is not defined in the changeName method. E The variable num is not defined in the addNum method.

E The variable num is not defined in the addNum method.

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

E When b has the value false

Consider the following class, which uses the instance variable balance to represent a bank account balance. public class BankAccount { private double balance; public double deposit(double amount) { /* missing code */ } } The deposit method is intended to increase the account balance by the deposit amount and then return the updated balance. Which of the following code segments should replace /* missing code */ so that the deposit method will work as intended? A amount = balance + amount; return amount; B balance = amount; return amount; C balance = amount; return balance; D balance = balance + amount; return amount; E balance = balance + amount; return balance;

E balance = balance + amount; return balance;

Consider the following code segment. int num = /* initial value not shown */; boolean b1 = true; if (num > 0) { if (num >= 100) { b1 = false; } } else { if (num >= -100) { b1 = false; } } 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);

E boolean b2 = (num < -100) || (num > 0 && num < 100);

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

E eeSepC

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

E 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? 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); }

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

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

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

On Sunday night, a meteorologist records predicted daily high temperatures, in degrees Fahrenheit, for the next seven days. At the end of each day, the meteorologist records the actual daily high temperature, in degrees Fahrenheit. At the end of the seven-day period, the meteorologist would like to find the greatest absolute difference between a predicted temperature and a corresponding actual temperature. /** Precondition: pred and act have the same non-zero length. */ public static int diff(int[] pred, int[] act) { int num = Integer.MIN_VALUE; for (int i = 0; i < pred.length; i++) { /* missing code */ } return num; } 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] -

E 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"); }

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

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

E newArray[k] = arr[arr.length - k - 1];

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;

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


Kaugnay na mga set ng pag-aaral

Chapter 64 - Nursing Management: Musculoskeletal Problems

View Set

Integrated Business Policy and Strategy - Exam 2

View Set

REG - ESTIMATED TAXES - Individual and Corporations

View Set

Ethics and Social Responsibility

View Set

Algebra I - Unit 1: Foundations of Algebra Quiz 2: The Real Numbers

View Set

FL Computations and Closing of Transactions

View Set

Chapter 22) 12&13 Seminal Vesicle and Prostate Gland

View Set