CSA P1

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Questions 27-28 refer to the following information. Consider the following sort method. This method correctly sorts the elements of array data into increasing order. public static void sort(int[] data) { for (int j = 0; j < data.length - 1; j++) { int m = j; for (int k = j + 1; k < data.length; k++) { if (data[k] < data[m]) /* Compare values */ { m = k; } } int temp = data[m]; /* Assign to temp */ data[m] = data[j]; data[j] = temp; /* End of outer loop */ } } Assume that sort is called with the array {6, 3, 2, 5, 4, 1}. What will the value ofdata be after three passes of the outer loop (i.e., when j = 2 at the point indicated by /* End of outer loop */) ? Select one: a. {1, 2, 3, 4, 5, 6} b. {1, 2, 3, 5, 4, 6} c. {1, 2, 3, 6, 5, 4} d. {1, 3, 2, 4, 5, 6} e. {1, 3, 2, 5, 4, 6}

The correct answer is b: {1, 2, 3, 5, 4, 6} The outer for loop loops through the entire array comparing left to right comparing the current number (outer loop) to the next number (inner loop) Swap does not occur till inner loop completes one full iteration through the array. In the first full pass numbers 1 & 6 get swapped. The variable m holds index of the smallest number as the inner loop completes.

Which of the following statements regarding interfaces is FALSE? Select one: a. All methods in an interface are public. b. An interface cannot be instantiated. c. An interface can declare an instance variable. d. A non-abstract class can implement an interface. e. An abstract class can implement an interface.

The correct answer is c. An interface can declare an instance variable.

Consider the following method. public static void showMe(int arg) { if (arg < 10) { showMe(arg + 1); } else { System.out.print(arg + " "); } } What will be printed as a result of the call showMe(0)? Select one: a. 10 b. 11 c. 0 1 2 3 4 5 6 7 8 9 d. 9 8 7 6 5 4 3 2 1 0 e. 0 1 2 3 4 5 6 7 8 9 10

The answer is A. 10 This is recursion. Nothing is printed until the 10th recursion call (10th time it calls itself). Then it prints the number 10 and a blank space. Stack unwinds and the program ends.

Consider the following method. public static boolean mystery(String str) { String temp = ""; for (int k = str.length(); k > 0; k--) { temp = temp + str.substring(k - 1, k); } return temp.equals(str); } Which of the following calls to mystery will return true ? Select one: a. mystery("no") b. mystery("on") c. mystery("nnoo") d. mystery("nono") e. mystery("noon")

Answer is e. mystery("noon") This is the answer as the method mystery processes through the string backwards, one character at a time. This is done by the substring (k -1, k). substring(int beginIndex, int endIndex) It creates a new string with each character it processes. Only a word that is spelled the same backwards as forwards would be equal to the source string and thus return a true boolean.

Questions 36-37 refer to the following information. Consider the following binarySearch method. The method correctly performs a binary search. /** Precondition: data is sorted in increasing order. */ public static int binarySearch(int[] data, int target) { int start = 0; int end = data.length - 1; while (start <= end) { int mid = (start + end) / 2; /* Calculate midpoint */ if (target < data[mid]) { end = mid - 1; } else if (target > data[mid]) { start = mid + 1; } else { return mid; } } return -1; } Consider the following code segment. int[] values = {1, 2, 3, 4, 5, 8, 8, 8}; int target = 8; What value is returned by the call binarySearch(values, target) ? Select one: a. -1 b. 3 c. 5 d. 6 e. 8

The correct answer is c. 5 Code starts out with a while loop with conditions using "start" and "end" variables. Array starts at zero and ends at last slot (data.length -1). The variable "mid" is calculated as (1 + 8) / 2 = 3 for the first pass of the while loop. Target is greater than value at mid slot (i.e. "4") so end = mid + 1. Recalculate the "mid" variable as (2 + 8) / 2 = 5. Target is equal to the value at mid slot (i.e. "8") so we have a hit on the search. Code returns the slot where the middle variable is, which is 5. Note that the return is the slot where the search match is, not the matched variable (i.e. "8").

Assume that x and y are boolean variables and have been properly initialized. (x && y) && !(x || y) Which of the following best describes the result of evaluating the expression above? Select one: 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

You got this one wrong. You selected E. I'd write this out on paper, going through each pass of the line of code from left to right. try with x and y set to true and false boolean values to see how it comes out. I'm going to say B: False always. I could be wrong. seems like given the second half is ! (i.e. not) then that makes this always false.

Consider the following recursive method. public static void whatsItDo(String str) { int len = str.length(); if (len > 1) { String temp = str.substring(0, len - 1); System.out.println(temp); whatsItDo(temp); } } What is printed as a result of the call whatsItDo("WATCH") ? Select one: a. H b. WATC c. ATCH ATC AT A d. WATC WAT WA W e. WATCH WATC WAT WA

The correct answer is D. WATC WAT WA W This is a recursive call code example. The example method "whatsItDo" takes in a string. The method code creates a string one character shorter than the string coming into the method (removes the last character with the substring from position 0 to the position one short of the final position in the string). This causes the string to get shorter and shorter with each call. The code (len > 1) ensures that when the string reaches one character the loop stops, the stack is unwound and the program ends.

Consider the following code segment. for (int r = 3; r > 0; r--) { int c; for (c = 1; c < r; c++) { System.out.print("-"); } for (c = r ; c <= 3; c++) { System.out.print("*"); } System.out.println(); } What is printed as a result of executing the code segment? Select one: a. --* -** *** b. *-- **- *** c. *** -** --* d. *** **- *-- e. --* *** --*

Answer is A. --* -** *** Write this out on your scrap paper to keep track of the print statement output with each pass through the loops. Pseudocode one side, output on the other side of the paper. Important! Outer loop is simple but counts down 3,2,1. Three passes. For the two inner loops. Note the value of "r". That determines the "*" or "-". Remember that print has no new line return but println does do a new line return.

Consider the following code segment. for (int outer = 1; outer <= 6; outer++) { for (int inner = outer; inner <= 6; inner++) { if (inner % 2 == 0) { System.out.print(inner + " "); } } System.out.println(); } What will be printed as a result of executing the code segment? Select one: a. 2 4 6 4 6 6 b. 2 4 6 2 4 6 2 4 6 c. 2 4 6 2 4 6 4 6 4 6 6 6 d. 2 4 6 2 4 6 2 4 6 2 4 6 2 4 6 2 4 6 e. 2 4 2 4 4 4

c. 2 4 6 2 4 6 4 6 4 6 6 6

Assume that x and y are boolean variables and have been properly initialized. (x || y) && x Which of the following always evaluates to the same value as the expression above? Select one: a. x b. y c. x && y d. x || y e. x != y

The answer is A. x

Consider the following definition. int[][] numbers = {{1, 2, 3}, {4, 5, 6}}; Which of the following code segments produces the output 123456 ? Select one: a. for (int[] row : numbers) { for (int n : row) { System.out.print(n); } } b. for (int[] row : numbers) { for (int n : row) { System.out.print(row[n]); } } c. for (int rc = 0; rc < numbers.length; rc++) { System.out.print(numbers[rc]); } d. for (int r = 0; r < numbers[0].length; r++) { for (int c = 0; c < numbers.length; c++) { System.out.print(numbers[r][c]); } } e. for (int c = 0; c < numbers[0].length; c++) { for (int r = 0; r < numbers.length; r++) { System.out.print(numbers[r][c]); } }

I think this problem is wrong. None of this code works. Letter E is the closest. Here is code that works to produce this output: for (int c = 0; c < numbers.length; c++) { for (int r = 0; r < numbers[c].length; r++) { System.out.print(numbers[c][r]); } } This is a two dimensional array. The first for loop checks for length of the number of occurrences in the outer array. That is the outer array. That's 2 occurrences. First occurence 1,2,3. Second occurence 4,5,6. The 'c' variable is used for the outer array. The inner array checks for length of the current instance of the outer array that it's about to iterate over. that's three. Both the inner arrays have three numbers each in them. The 'r' variable is used for the inner array. The problem asks for output 1,2,3,4,5,6. That's printing out the first occurrence array, all variables, then printing the second occurrence array, all variables. This print statement does that.

Consider the following method, biggest, which is intended to return the greatest of three integers. It does not always work as intended. public static int biggest(int a, int b, int c) { if ((a > b) && (a > c)) { return a; } else if ((b > a) && (b > c)) { return b; } else { return c; } } Which of the following best describes the error in the method? Select one: 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.

The answer is C. biggest may not work correctly when a and b have equal values. This code is bad as it never addresses when one of more of the numbers are the same. Example: 4,4,3 are the three numbers. The issue is that is the first and second number are the same and larger than the third, the code does not work for this scenario. The first if check fails. The second if check also fails as a = b. You needed one of these to work as the method just returns 'c' if the first two fail.

Consider the following method. //* Precondition: num > 0 */ public static int doWhat(int num) { int var = 0; for (int loop = 1; loop <= num; loop = loop + 2) { var += loop; } return var; } Which of the following best describes the value returned from a call to doWhat ? Select one: a. num b. The sum of all integers between 1 and num, inclusive c. The sum of all even integers between 1 and num, inclusive d. The sum of all odd integers between 1 and num, inclusive e. No value is returned because of an infinite loop.

The answer is D. The sum of all odd integers between 1 and num, inclusive. Write this out on your scrap paper to keep track of the variables with each pass through the loop. This for loop will have the variable 'loop' be set as odd numbers 1,3,5,7,9 etc... for each pass through the loop as loop = loop + 2; The var+=loop is adding the previous calculated value. First pass variables loop = 1 and var = 0; 0+1=1 1+3 = 4 4+5 = 9 9+7=16

Consider the following method. /** Precondition: arr.length > 0 */ public static int mystery(int[] arr) { int index = 0; int count = 0; int m = -1; for (int outer = 0; outer < arr.length; outer++) { count = 0; for (int inner = outer + 1; inner < arr.length; inner++) { if (arr[outer] == arr[inner]) { count++; } } if (count > m) { index = outer; m = count; } } return index; } 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)? Select one: 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

The answer is E. An index of a value that occurs most often in nums. In this code the outer four loop and the inner for loop are used to compare the current number in the array to all other numbers in the array. The inner loop starts one number higher in the array (int inner = outer + 1). That gives the comparison if statement in the inner loop the correct array counter values (outer vs. inner). The 'm' variable is a holder for the max number of duplicates found to date in the run of the program. It's -1 initially. It always gets set once (first pass through). It gets set again if a higher number of duplicates is found as it continues to process through the array. The index variable holds the index of the first occurance if the number that appears most in the array.

Consider the following code segment. int x = 1; while ( /* condition */ ) { if (x % 2 == 0) { System.out.print(x + " "); } x = x + 2; } The following conditions have been proposed to replace /* condition */ in the code segment. I. x < 0 II. x <= 1 III. x < 10 For which of the conditions will nothing be printed? Select one: a. I only b. II only c. I and II only d. I and III only e. I, II, and III

The answer is E. I, II, and III None of these produce output! For I - It will never enter the while block if x < 0 For II - It will enter the while block one time. The remainder of 1 % 2 is not zero so it will not print the value of x. For III - It will enter the block and loop 5 times. The x variable will be set to 1,3,5,7,9 for each pass of the loop. That is because x will be incremented by 2 with each pass (x=x+2 final line in the block). So, due to that, the x % 2 calculation is always an odd number, not divisible by 2 to a remainder will always be present. Due to this, no output will be produced by this condition either.

Suppose the binarySearch method is called with an array containing 2,000 elements sorted in increasing order. What is the maximum number of times that the statement indicated by /* Calculate midpoint */ could execute? Select one: a. 2,000 b. 1,000 c. 20 d. 11 e. 1

The answer is d. 11. Note that binary search can be done only in a sorted array. It states that the array is sorted. The worst case of a binary search is when you search for the first element or the last element in the array or search for an element which does not exist in the array and is lower than the first element in the array or higher than the last element in the array. This is because we always compare the element we search with the middle element in any range. The accurate no. of comparisons depends on how you implement your binary search. But it is appx. equal to log2(2000) which is appx. 11 comparisons. In case there are other values on the test, here are the logs for those. I think you want to always round up to the next whole number. 1,000 = 9.96 or 10 2,000 = 10.96 or 11 3,000 = 11.55 or 12 4,000 = 11.96 or 12 5,000 = 12.28 or 13 10,000 = 13.28 or 14 20,000 = 14.28 or 15

Consider the following interface and class declarations. public interface Student { /* implementation not shown */ } public class Athlete { /* implementation not shown */ } public class TennisPlayer extends Athlete implements Student { /* implementation not shown */ } Assume that each class has a zero-parameter constructor. Which of the following is NOT a valid declaration? Select one: a. Student a = new TennisPlayer(); b. TennisPlayer b = new TennisPlayer(); c. Athlete c = new TennisPlayer(); d. Student d = new Athlete(); e. Athlete e = new Athlete();

The answer to this is D: You cannot create a student object from an athlete. There is no relationship for that. For A, you can create a Student from a TennisPlayer as TennisPlayer implements the interface Student. B and E are both OK. You can create an object from that object (i.e. TennisPlayer from TennisPlayer or Athlete from Athlete. For C, you can create an Athlete from a TennisPlayer as TennisPlayer extends the Athlete class.

Consider the following code segment. String[ ][ ] board = new String[5][5]; for (int row = 0; row < 5; row++) { for (int col = 0; col < 5; col++) { board[row][col] = "O"; } } for (int val = 0; val < 5; val++) { if (val % 2 == 1) { int row = val; int col = 0; while (col < 5 && row >= 0) { board[row][col] = "X"; col++; row--; } } } Which of the following represents board after this code segment is executed? Select one: a. . 0 1 2 3 4 0 x o x o x 1 o x o x o 2 x o x o x 3 o x o x o 4 x o x o x b. . 0 1 2 3 4 0 o x o x o 1 x o x o x 2 o x o x o 3 x o x o x 4 x o x o x c. . 0 1 2 3 4 0 x o o o x 1 o x o x o 2 o o x o o 3 o x o x o 4 x o o o x d. . 0 1 2 3 4 0 o x o o o 1 o o x o o 2 x o o x o 3 o x o o x 4 o o x o o e. . 0 1 2 3 4 0 o x o x o 1 x o x o o 2 o x o o o 3 x o o o o 4 o o o o o

The correct answer is "e". The first "for" loop has an inner "for" loop and populates the entire 5x5 array with with "O". The code then has another "for" loop that loops through the numbers 0 to 4. The "for" loop ends when val = 5. The "if" condition checks for remainders = 1. The numbers 1 and 3 will produce a remainder of 1 in the range of 0 to 4. The "while" statement starts with the row variable set to the number '1' with the first pass. An "X" is set in [1][0]. the col variable is increased but the row variable is decreased. Given the while condition is "(col < 5 && row >= 0)" and col++ and row-- there will be one additional pass through the while block code before it exits. An "X" is set in [0][1]. The row variable is now 0 so the while loop ends. The "while" statement runs the second and last time with the row variable set to the number '3'. as the code is col++ and row-- here's what gets set: X at row 3 col 0 X at row 2 col 1 X at row 1 col 2 X at row 0 col 3 The program ends at this point as only the numbers 1 and 3 will produce a remainder of 1 in the range of 0 to 4.

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 ofwords and should appear in reverse order in the resulting string. /** Precondition: words.length > 0; * startIndex >= 0 */ public static String concatWords(String[] words, int startIndex) { String result = ""; /* missing code */ return result; } For example, the following code segment uses a call to the concatWords method. String[] things = {"Bear", "Apple", "Gorilla", "House", "Car"}; System.out.println(concatWords(things, 2)); When the code segment is executed, the string "CarHouseGorilla" is printed. The following three code segments have been proposed as replacements for /* missing code */. I. for (int k = startIndex; k < words.length; k++) { result += words[k] + words[words.length - k - 1]; } II. int k = words.length - 1; while (k >= startIndex) { result += words[k]; k--; } III. String[] temp = new String[words.length]; for (int k = 0; k <= words.length / 2; k++) { temp[k] = words[words.length - k - 1]; temp[words.length - k - 1] = words[k]; } for (int k = 0; k < temp.length - startIndex; k++) { result += temp[k]; } Which of these code segments can be used to replace /* missing code */ so that concatWords will work as intended? Select one: a. I only b. II only c. III only d. I and II e. II and III

The correct answer is 3. II and III Option I is incorrect. It starts at the starting index and starts to build the string from there. that is incorrect as correct string must start at the end of the array and work backwards to the starting index. Option II is correct. It starts at the end of the array and builds the result string going backwards (i.e. k--) until until k increments less than the start index. Then it stops. This is the best code of the three options. Option III is also correct. This is very messy code that just barely works given the start index of 2. It starts by creating a new temp string, which is not necessary but OK at this point. The first loop only works because this loop will process three times before (k <= words.length / 2). First pass Length is 5 - 0 - 1 = 4. Variable "temp" assigns "Car" to it. Next pass 5 - 1 - 1 = 3 Variable "temp" appends "House" to it. Next pass 5 - 2 - 1 = 2 Variable "temp" appends "Gorilla" to it. For loop stops at that point. Second four loop simply copies over each slot in the temp array into the result array. Final line in method returns result array back.

Consider the following class. public class SomeMethods { public void one(int first) { /* implementation not shown */ } public void one(int first, int second) { /* implementation not shown */ } public void one(int first, String second) { /* implementation not shown */ } } Which of the following methods can be added to the SomeMethods class without causing a compile-time error? I. public void one(int value) { /* implementation not shown */ } II. public void one(String first, int second) { /* implementation not shown */ } III. public void one(int first, int second, int third) { /* implementation not shown */ } Select one: a. I only b. I and II only c. I and III only d. II and III only e. I, II, and III

The correct answer is D. II and III only The reason that II and III can be added to the class without creating a compile time error is because they are new methods with new signatures. In the case of I that method it's really a change to an existing method so programs that use this class need to be recompiled.

What is printed as a result of executing the following statement? System.out.println(404 / 10 * 10 + 1); Select one: a. 4 b. 5 c. 41 d. 401 e. 405

The correct answer is D: Operator precedence rules: Group 1 - Multiplication and division have the highest precedence. Group 2 - Addition and subtraction next highest. Group 3 - Equals is evaluated last. Multiplication / Division / Remainder * / % these are evaluated left to right within this group Addition / Subtraction + - these are evaluated left to right within this group Assignment (i.e. = ) = Evaluated last When two operators share an operand the operator with the higher precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition. How we get this to calculate out to 401 404 / 10 * 10 +1 404 / 10 = 40 40 * 10 = 400 400 + 1 = 401 401 is the answer

Consider the following recursive method. /** Precondition: num ≥ 0 */ public static int what(int num) { if (num < 10) { return 1; } else { return 1 + what(num / 10); } } Assume that int val has been declared and initialized with a value that satisfies the precondition of the method. Which of the following best describes the value returned by the call what(val) ? Select one: a. The number of digits in the decimal representation of val is returned. b. The sum of the digits in the decimal representation of val is returned. c. Nothing is returned. A run-time error occurs because of infinite recursion. d. The value 1 is returned. e. The value val/10 is returned.

The correct answer is a: The number of digits in the decimal representation of val is returned. This is true for all use cases. First, if the number passed in is less than 10 it returns a '1' for a single digit number. When it's a number greater than 10 with recursion the "else" condition hits and it will continue to call the "what" function until the number divided by 10 is less than ten. The return code "return 1 + what(num / 10);" adds up the multiple return values from the recursive calls to add up the digits. So, for example, with the number that is three digits like 400 it will take two additional calls to the "what" function.

Consider the following class declaration. public class StudentInfo { private String major; private int age; public String getMajor() { return major; } public int getAge() { return age; } // There may be instance variables, constructors, and methods that are not shown. } The following instance variable and method appear in another class. private List<StudentInfo> students; /** @return the average age of students with the given major; * -1.0 if no such students exist */ public double averageAgeInMajor(String theMajor) { double sum = 0.0; int count = 0; for (StudentInfo k : students) { /* missing code */ } if (count > 0) { return sum / count; } else { return -1.0; } } Which of the following could be used to replace /* missing code */ so that averageAgeInMajor will compile without error? Select one: a. if (theMajor.equals(k.major)) { sum += k.age; count++; } b. if (theMajor.equals(k.getMajor())) { sum += k.getAge(); count++; } c. if (theMajor.equals(k.major)) { sum += k.getAge(); count++; } d. if (theMajor.equals(students[k].getMajor())) { sum += students[k].getAge(); count++; } e. if (theMajor.equals(getMajor(k))) { sum += getAge(k); count++; }

The correct answer is b. b. if (theMajor.equals(k.getMajor())) { sum += k.getAge(); count++; } The variable "theMajor" is a string so a string compare must be done on the current instance of students in the array. They use the "getMajor" method to get the major from the students list. Note that the "for" statement iterates over "students" and allows for a reference to an object of type "StudentInfo" inside the "for" block code. You can at get the class instance variables for each instance via calls to the methods for the class. Examples: k.getAge(); k.getMajor(); If the instance of student matches the major passed into "averageAgeInMajor" method the code next gets the age from the current instance of students in the array using the "getAge" method. The code: sum += k.getAge(); adds the age into the sum variable. The count is incremented "count++;" to indicate the numbers of students to calculate the average for.

Assume that sort is called with the array {1, 2, 3, 4, 5, 6}. How many times will the expression indicated by /* Compare values */ and the statement indicated by /* Assign to temp */ execute? Compare values Assign to temp Select one: a. 15 0 b. 15 5 c. 15 6 d. 21 5 e. 21 6

The correct answer is b. 15 5 The "Compare Values" comparison is checked each time the current variable is compared against the remaining in the array. There are six numbers in the array so that's five compares (j < data.length - 1) is 5 in a six slot array. Given the array {1, 2, 3, 4, 5, 6}, the first pass for "1" does five comparisons. The second pass for "2" would do four comparisons. In total for all would be 15. Like this: 5 + 4 + 3 + 2 + 1 = 15. "Assign to temp" is done within the outer loop to switch any numbers as the inner loop as iterated through the array. The switch is only needed once for each slot or index in the array. This execute 5 times in a six slot array. Thus the answer is 'b', 15 and 5.

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. Number of Boxes Price per Box 1 up to but not including 5 $5.00 5 up to but not including 10 $3.00 10 or more $1.50 The following incomplete method is intended to return the total cost of an order based on the value of the parameter numBoxes. /** Precondition: numBoxes > 0 */ public static double getCost(int numBoxes) { double totalCost = 0.0; /* missing code */ return totalCost; } Which of the following code segments can be used to replace /* missing code */so that methodgetCost will work as intended? I. if (numBoxes >= 10) { totalCost = numBoxes * 1.50; } if (numBoxes >= 5) { totalCost = numBoxes * 3.00; } if (numBoxes > 0) { totalCost = numBoxes * 5.00; } II. if (numBoxes >= 10) { totalCost = numBoxes * 1.50; } else if (numBoxes >= 5) { totalCost = numBoxes * 3.00; } else { totalCost = numBoxes * 5.00; } III. if (numBoxes > 0) { totalCost = numBoxes * 5.00; } else if (numBoxes >= 5) { totalCost = numBoxes * 3.00; } else if (numBoxes >= 10) { totalCost = numBoxes * 1.50; } Select one: a. I only b. II only c. III only d. I and II e. II and III

The correct answer is b. II only Code chunk I does not work because every "if" statement will be checked. Code chunk II does work because the code uses "if" and "if else" statements. It starts with the condition for the highest number range first then goes down. Code chunk III does not work because the first if statement simply does > 0. That will take all counts > 0 and apply the $5 a box price range which is incorrect.

Consider the following code segment. List<String> students = new ArrayList<String>(); students.add("Alex"); students.add("Bob"); students.add("Carl"); for (int k = 0; k < students.size(); k++) { System.out.print(students.set(k, "Alex") + " "); } System.out.println(); for (String str : students) { System.out.print(str + " "); } What is printed as a result of executing the code segment? Select one: a. Alex Alex Alex Alex Alex Alex b. Alex Alex Alex Alex Bob Carl c. Alex Bob Carl Alex Alex Alex d. Alex Bob Carl Alex Bob Carl e. Nothing is printed because the first print statement will cause a runtime exception to be thrown.

The correct answer is c. The first "for" block is doing two things at once. first, it's setting each existing slot in the students array to "Alex". There's a key thing to understand about how the "set" method on an Array works. When calling the "set" method on the students list the element that previously existed at the specified index is returned. This is why the first output that you see is "Bob" when it's replaced with "Alex" and "Carl" when it's replaced with "Alex". "Alex Bob Carl" is first output you will see from this line System.out.print(students.set(k, "Alex") + " "); When the second "for" block executes, the array is now populated with "Alex Alex Alex" from the previous "for" block so all you will see is... "Alex Alex Alex" This is the reason why c is the correct answer.

Consider the following method. /** Precondition: 0 < numVals <= nums.length */ public static int mystery(int[] nums, int v, int numVals) { int k = 0; if (v == nums[numVals - 1]) { k = 1; } if (numVals == 1) { return k; } else { return k + mystery(nums, v, numVals - 1); } } Which of the following best describes what the call mystery(numbers, val, numbers.length) does? You may assume that variables numbers and val have been declared and initialized. Select one: a. Returns 1 if the last element in numbers is equal to val; otherwise, returns 0 b. Returns the index of the last element in numbers that is equal to val c. Returns the number of elements in numbers that are equal to val d. Returns the number of elements in numbers that are not equal to val e. Returns the maximum number of adjacent elements that are not equal to val

The correct answer is c. Returns the number of elements in numbers that are equal to val Recursion is used here. The first "if" block in the code checks to see if there is a match of the search variable (i.e. "v") to the last variable in the array (as indicated by numVals - 1). Note that because this is recursive each call to mystery will back up this up one lower in the array. The second "if" block checks to see if the array is only one long. If that's the case, return and end. There is no more to process in the array. The else of the second "if" block calls mystery again, but this time sets the numVals length one shorter. The mystery method runs again. If there is a match (i.e. first "if" block is true), k = 1 meaning that when the stack unwinds 1 will be added to the overall return value. The code... return k + mystery(nums, v, numVals - 1); Adds the returned "1" to the existing value if 'k' from the underlying call in the stack. This is how the code returns the number of elements in the variable numbers array that are equal to the value of the val variable. That is why the correct answer is c.

Consider the following code segment. int count = 0; for (int x = 0; x < 4; x++) { for (int y = x; y < 4; y++) { count++; } } System.out.println(count); What is printed as a result of executing the code segment? Select one: a. 4 b. 8 c. 10 d. 16 e. 20

The correct answer is c: 10. The trick to understanding this code is realizing that the inner loop starts at y = x or the same index as the outer loop. The inner loop is one less pass for each increment of the outer loop. This is NOT 5x5=25!!! For the 0 index, the count does +1 four times so the count goes one, two three, four. For the 1 index, the count does +1 three times (1-3) so the count goes five, size, seven. For the 2 index, the count does +1 twice (2-3) so the count goes eight, nine. For the 3 index we only get one pass as the for loop is checking for < 4. The count does +1 once so the count goes to ten. That's the end of the loop. The println runs once and prints out the current value of the count variable which is 10.

Consider the following instance variable and method. Method wordsWithCommas is intended to return a string containing all the words in listOfWords separated by commas and enclosed in braces. For example, if listOfWords contains ["one", "two", "three"], the string returned by the call wordsWithCommas() should be "{one, two, three}". private List<String> listOfWords; public String wordsWithCommas() { String result = "{"; int sizeOfList = /*expression */ ; for (int k = 0; k < sizeOfList; k++) { result = result + listOfWords.get(k); if ( /* condition */ ) { result = result + ", "; } } result = result + "}"; return result; } Which of the following can be used to replace two chunks of code: /* expression */ and /* condition */ so that method wordsWithCommas will work as intended? Select one: /* expression */ /* condition */ a. listOfWords.size() - 1 k != 0 b. listOfWords.size() k != 0 c. listOfWords.size() - 1 k != sizeOfList - 1 d. listOfWords.size() k != sizeOfList - 1 e. result.length() k != 0

The correct answer is d. /* expression */ /* condition */ listOfWords.size() k != sizeOfList - 1 The "expression" code to set the sizeOfList int variable is "listOfWords.size()" This sets the sizeOfList variable to the true number of instances in the list. If there are four items in the list then it is set to four. This leaves you with options "b" or "d". It's important to note that the code: listOfWords.size() - 1 Could also be used for "expression" but the corresponding value for "condition must also work. Given the "expression" code is set the way that it is, the "condition" code is set check for the variable sizeOfList -1. This is important as the for loop starts at k = 0. If you chose options "a" or "c" for "expression", the corresponding "condition" code for "a" definitely does not work. The first pass k = 0 so the first word would get missed. For option "c" the condition code of "k != sizeOfList - 1" would not work with the length set differently.

Consider the following two methods, which appear within a single class. public static void changeIt(int[] arr, int val, String word) { arr = new int[5]; val = 0; word = word.substring(0, 5); for (int k = 0; k < arr.length; k++) { arr[k] = 0; } } public static void start() { int[] nums = {1, 2, 3, 4, 5}; int value = 6; String name = "blackboard"; changeIt(nums, value, name); for (int k = 0; k < nums.length; k++) { System.out.print(nums[k] + " "); } System.out.print(value + " "); System.out.print(name); } What is printed as a result of the call start() ? Select one: a. 0 0 0 0 0 0 black b. 0 0 0 0 0 6 blackboard c. 1 2 3 4 5 6 black d. 1 2 3 4 5 0 black e. 1 2 3 4 5 6 blackboard

The correct answer is e: e. 1 2 3 4 5 6 blackboard This is a tricky one!!! The first thing to look at is that there are no class instance variables here. They are all in the start method. They only exist in the scope of the start method. The next thing to look at with the two methods is that the only print statements are in the start method and the signature on the "changeIt" method is a void return. This shows that while the nums variable, value variable and name variable = "blackboard" is passed in there is no modification of those variables in "changeIt". Choices a,c, and d should be immediately ruled out as there is no modification of "name" after it is defined at the top of the start method. All lines below that in the start method simply print out the variables. The nums array is printed, then the value of the value variable then the value of the name variable. So, none of variables in the start method are modified after they are defined. They are just printed out. Tricky!!!

Consider the following method. public static int[] operation(int[][] matrix, int r, int c) { int[] result = new int[matrix.length]; for (int j = 0 ; j < matrix.length ; j++) { result[j] = matrix[r][j] * matrix[j][c]; } return result; } The following code segment appears in another method in the same class. int[][] mat = {{3,2,1,4}, {1,2,3,4}, {2,2,1,2}, {1,1,1,1}}; int[] arr = operation(mat, 1, 2); Which of the following represents the contents of arr as a result of executing the code segment? Select one: a. {6,4,2,4} b. {1,6,3,4} c. {4,3,6,1} d. {4,4,2,2} e. {2,2,4,4}

b. {1,6,3,4} Use paper to figure this out out. Write out the 'mat' variable in a grid on a piece of paper. It's the 4x4 grid of numbers. The grid is passed into the "operation" method. Look at the two numbers passed in (1,2). These fill the variables r and c in the method signature. Walk through the loop multiplying the two numbers identified in the matrix [r][j] * matrix [j] [c] to get the result. Each pass (i.e. four passes) creates one of the numbers in the four number sequence result. Iterations are: 1 * 1 = 1 2 * 3 = 6 3 * 1 = 3 4 * 1 = 4 This gives you the answer "b" {1,6,3,4}

Consider the following two classes. public class A { public void show() { System.out.print("A"); } } public class B extends A { public void show() { System.out.print("B"); } } What is printed as a result of executing the following code segment? A obj = new B(); obj.show(); Select one: a. A b. B c. AB d. BA e. The code results in a runtime error.

The answer is B. B Class B extends A and the show method has the same signature. The first line of code creates an instance of the class A but uses the B class constructor. That creates the instance looking like B rather than A. Thus, in the next line when you call the method "show" on that object you get the "show" method from B.

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. I. int max = Integer.MIN_VALUE; for (int value : arr) { if (max < value) { max = value; } } II. int max = 0; boolean first = true; for (int value : arr) { if (first) { max = value; first = false; } else if (max < value) { max = value; } } III. int max = arr[0]; for (int k = 1; k < arr.length; k++) { if (max < arr[k]) { max = arr[k]; } } Which of the code segments will always correctly assign the maximum element of the array to the variable max ? Select one: a. I only b. II only c. III only d. II and III only e. I, II, and III

The correct answer is e. I, II, and III All code segments will work properly. For segment I, max is initialized to the minimum value from the Integer class. That's good. Next, the for loop iterates through the array comparing max to value where value is the current value in the array. The variable max is replaced with value when max is less than value (meaning a new max value is found). For segment II, the code is almost the same as I but there's a flag used for the first pass through the for loop code. Since max is initialized to zero the initial "if" check works. the next "else if" would also work. The end result is the same as I. For segment III, the variable max is initialized with the first value in the array. The "for loop starts at the second number in the array, which is at position 1. The "if" statement compares the max variable and the current instance of arr we are iterating over. the max variable is set to that instance if max is less. The end result is the same as II and III.

Consider the following instance variable and method. private int[] numbers; public void mystery(int x) { for (int k = 1; k < numbers.length; k = k + x) { numbers[k] = numbers[k - 1] + x; } } 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) ? Select one: 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}

The answer is A. {17, 20, 21, 42, 45, 69, 48, 51, 39} Write this out on your scrap paper to keep track of the variables with each pass through the loop. So, 3 is the number passed into the method. First pass starts at position 1, as indicated in the four loop. That is 34. So, 17 remains the first number at position 0. ? = 17 + 3 which is 20. 2nd slot in numbers array is now 20. For loop's incrementer is k = k + 3, so 1 + 3 = 4. ? = 42 + 3 which is 45. 4th slot in numbers array is now 45. For ? = 42 + 3 which is 45. 4th slot in numbers array is now 45., so 4 + 3 = 7. ? = 48 + 3 which is 51. 7th slot in numbers array is now 51. The loop ends as loop's incrementer is k = k + 3, so 7 + 3 = 10 which is > 8, the array length. The loop ends.

Consider the following method, which is intended to return true if at least one of the three strings s1, s2, or s3 contains the substring "art".; Otherwise, the method should return false. public static boolean containsArt(String s1, String s2, String s3) { String all = s1 + s2 + s3; return (all.indexOf("art") != -1); } Which of the following method calls demonstrates that the method does not work as intended? Select one: a. containsArt ("rattrap", "similar", "today") b. containsArt ("start", "article", "Bart") c. containsArt ("harm", "chortle", "crowbar") d. containsArt ("matriculate", "carat", "arbitrary") e. containsArt ("darkroom", "cartoon", "articulate")

a. containsArt ("rattrap", "similar", "today") This is because the "art" is found as a combination of "similar" and "today". That is not as intended based upon the description of what the method should do.

Consider the following instance variable and method. private int[] arr; /** Precondition: arr.length > 0 * @return the largest value in array arr */ public int findMax() { int maxVal = 0; for (int val : arr) { if (val > maxVal) { maxVal = val; } } return maxVal; } 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? Select one: 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 answer is C. The largest value in arr is negative. This is because the code initializes the maxVal to zero. If all numbers in the array are zero since the check is for > maxVal, which is zero it will never set maxVal for a negative number. Thus maxVal will remain zero passing through the entire loop.

Consider the following method. /** Precondition: values has at least one row */ public static int calculate(int[][] values) { int found = values[0][0]; int result = 0; for (int[] row : values) { for (int y = 0; y < row.length; y++) { if (row[y] > found) { found = row[y]; result = y; } } } return result; } Which of the following best describes what is returned by the calculate method? Select one: a. The largest value in the two-dimensional array b. The smallest value in the two-dimensional array c. The row index of an element with the largest value in the two-dimensional array d. The row index of an element with the smallest value in the two-dimensional array e. The column index of an element with the largest value in the two-dimensional array

Answer is E. The column index of an element with the largest value in the two-dimensional array. Here is an example two dimensional array. int[][] numbers = {{17, 34, 21}, {42, 15, 69}, {48, 25, 39}}; The code initialized the variable 'found' to 17, the number at 0,0 (row,column) in this two dimensional array. This is the first number in the array. The code has two for loops. The first for loop is for rows. The second for loop is for columns. The if check in the inner loop looks for numbers greater than 'found', which is initialized to 17. The largest number is 69, it is in 3rd column of row 2. Index starts at zero so it returns back 2.

Consider the following incomplete method, which is intended to return the number of integers that evenly divide the integer inputVal. ; Assume that inputVal is greater than 0. public static int numDivisors(int inputVal) { int count = 0; for (int k = 1; k <= inputVal; k++) { if ( /*condition*/ ) { count++; } } return count; } Which of the following can be used to replace /*condition*/ so that numDivisors will work as intended? Select one: a. inputVal % k== 0 b. k % inputVal == 0 c. nputVal % k != 0 d. inputVal / k == 0 e. k / inputVal > 0

a. inputVal % k== 0

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

I think the answer is a. You got it wrong. It should work like this. The Math.random() returns a value between 0.0 and 1.0. That is multiplied by 6 to give you a value of 1-6. Multiply that *2 and that gives you a max of 12.

Consider the following code segment from an insertion sort program. for (int j = 1; j < arr.length; j++) { int insertItem = arr[j]; int k = j - 1; while (k >= 0 && insertItem < arr[k]) { arr[k + 1] = arr[k]; k--; } arr[k + 1] = insertItem; /* end of for loop */ } Assume that array arr has been defined and initialized with the values {5, 4, 3, 2, 1}. What are the values in array arr after two passes of the for loop (i.e., when j = 2 at the point indicated by /* end of for loop */) ? Select one: a. {2,3,4,5,1} b. {3,2,1,4,5} c. {3,4,5,2,1} d. {3,5,2,3,1} e. {5,3,4,2,1}

The correct answer is c. {3,4,5,2,1} This code is sorting the array of numbers to smallest to largest left to right. It's currently opposite this. It's doing this by comparing two numbers at a time and swapping them as it iterates through the array. The for loop sets the "insertItem" as the second number in the pair. It holds that number (not the index). This next part is in a while loop... If the first number index (i.e. k variable) >= 0 (which means we are at least at the start of the pairs of numbers at the start of the array) and insertItem (i.e. the second number) is less than the first number (which is currently at 'k' index), then set the second number in the pair equal to the first number (which is currently at 'k' index). This is essentially flipping pairs of numbers through the array going backwards. The while loop continues backwards in the array till it gets to the start. This is the reason for that k >= 0 check. Notice that Once the while loop finishes it's number comparison all the way back to the front of the array, the "insertItem" is set to arr[k+1]. This is actually the zero position as the while loop continues to loop backwards with k-- as the last line of code in the loop. It's at -1 when the final pass of the while loop ends. As the problem asks for what the array looks like after two passes (i.e. j = 2) the number '5' will have moved two places to the right in the array and "3" and "4" has shifted left as they are less than "5".


संबंधित स्टडी सेट्स

Встановлення комуністичного тоталітарного режиму в Україні

View Set

PHTH 550 - Sensitivity & Specificity

View Set

Solutions to Chapter Questions (2, 3, 4, 5, 9)

View Set

CH17. Information Security: Barbarians at the Gateway (and Just About Everywhere Else)

View Set

Time is an important variable in many psychological concepts. Describe a specific example that clearly demonstrates an understanding of each of the following concepts and how it relates to or is affected by time. Use a different example for each concept.

View Set