APCSA Quiz 8 Review

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

93) Based on the code snippet, which of the following statements is correct? public static void reoccur(int count) { System.out.println(count); reoccur(count + 1); } public static void main(String[] args) { reoccur(1); } a) The code snippet gives a compilation error as the reoccur method cannot call itself. b) The code snippet executes and infinitely recurses, displaying 1, 2, 3, 4, and so on. c) The code snippet executes and displays 1. d) The code snippet executes and does not produce any output.

b) The code snippet executes and infinitely recurses, displaying 1, 2, 3, 4, and so on.

What is the error in the following method definition? public static void findMin(int x, int y) { int min = 0; if (x < y) { min = x; } else { min = y; } } a) The method returns the maximum instead of the minimum of the two arguments. b) The method does not return a value. c) The method returns 0 if the first and second arguments are equal. d) The method does not specify a type for the second argument.

b) The method does not return a value.

13) What is stepwise refinement? a) The process of unit testing b) The process of breaking complex problems down into smaller, manageable steps c) The design of pseudocode for black-box methods d) The use of a temporary implementation of a method that can be improved later

b) The process of breaking complex problems down into smaller, manageable steps

12) The purpose of a method that returns void is a) To satisfy compiler warnings b) To package a repeated task as a method even though the task does not yield a value c) To force a value to be returned in case the "return" statement is forgotten d) To insert a temporary implementation of a method that can be refined later

b) To package a repeated task as a method even though the task does not yield a value

24) Consider a method named avg, which accepts four numbers as integers and returns their average as a double. Which of the following is a correct call to the method avg? a) avg(2, 3.14, 3, 5); b) double average = avg(2, 3, 4, 5); c) avg(); d) double average = avg("2", "3", "4", "5");

b) double average = avg(2, 3, 4, 5);

27) The Java method Math.round can be used to round numbers. Which of the following code fragments converts a floating-point number to the nearest integer? a) double f = 4.65; int n = (int) Math.round(100 * f); b) double f = 4.65; int n = (int) Math.round(f); c) double f = 4.65; int n = Math.round(f); d) double f = 4.65; int n = (int) f;

b) double f = 4.65; int n = (int) Math.round(f)

public static int fun(int x) { int returnValue = 0; if (x > 5) { returnValue = x; } else { returnValue = fun(2 * x); } return returnValue; } public static void main(String[] args) { System.out.println("fun(2) = " + fun(2)); } a) fun(2) = 4 b) fun(2) = 8 c) fun(2) = 16 d) fun(2) = 32

b) fun(2) = 8

31) Consider a method named calc, which accepts two numbers as integers and returns their sum as an integer. Which of the following is the correct statement to invoke the method calc? a) calc(2, 3.14); b) int sum = calc(2, 3); c) calc(); d) int sum = calc("2", "3");

b) int sum = calc(2, 3);

43) What are the values of num1 and num2 and result after executing the code snippet below? public static int mystery (int firstNum, int secondNum) { firstNum = firstNum * 2; secondNum = secondNum * 3; return firstNum + secondNum; } public static void main(String[] args) { int num1 = 10; int num2 = 11; int result = mystery(num1, num2); } a) num1 = 20, num2 = 33 and result is 53 b) num1 = 10, num2 = 11 and result is 53 c) num1 = 0, num2 = 0 and result is 0 d) num1 = 20, num2 = 33 and result is 0

b) num1 = 10, num2 = 11 and result is 53

38) Which of the following is the correct header for a greaterThan method definition that takes two arguments of type double and returns true if the first value is greater than the second value? a) public static int greaterThan(double a, double b) b) public static boolean greaterThan(double a, double b) c) public static double greaterThan(boolean a, boolean b) d) public static boolean greaterThan(double a, b)

b) public static boolean greaterThan(double a, double b)

39) Suppose you need to write a method that calculates the volume of a 3D rectangular solid. Which of the following is the best choice for the declaration of this method? a) public static void volume(int a) b) public static double volume(double w, double h, double l) c) public static void volume(double w, double h, double l) d) public static double volume(double w)

b) public static double volume(double w, double h, double l)

98) Which method header is appropriate for this method body? { if (num1 < num2) { return num1; } return num2; } a) public static void comp(int num1, int num2) b) public static int comp(int num1, int num2) c) public static boolean comp(int num1, int num2) d) public static int comp(int num1, double num2)

b) public static int comp(int num1, int num2)

67) Which of the following code snippets can be used for defining a method that does not return a value? The method should accept a string and then display the string followed by "And that's all folks!" on a separate line. a) public static String displayMessage(String str) { System.out.println(str); System.out.println("And that's all folks!"); } b) public static void displayMessage(String str) { System.out.println(str); System.out.println("And that's all folks!"); } c) public static void displayMessage(String str) { System.out.println(str); System.out.println("And that's all folks!"); return str; } d) public static void displayMessage() { System.out.println(str); System.out.println("And that's all folks!"); }

b) public static void displayMessage(String str) { System.out.println(str); System.out.println("And that's all folks!"); }

40) What can be used as an argument in a method call? I. A variable II. An expression III. Another method call that returns a value IV. Another method call that has no return value a) I only b) I and II c) I, II and III d) III and IV

c) I, II and III

79) Given the following method: public static boolean isMagic(int number) { int j = 2; boolean result = false; while (j <= number / 2) { if (number % j == 0) { result = true; } j++; } return result; } What argument(s) will cause the result of the method to be true? I. 197 II. 224 III. 231 IV. 341 a) I and II b) II and III c) II, III, and IV d) I and III

c) II, III, and IV

33) In an accounting application, you discover several places where the total profit, a double value, is calculated. Which of the following should be done to improve the program design? I. The next time the total profit is calculated, use copy and paste to avoid making coding errors. II. Provide the same comment every time you repeat the total profit calculation. III. Consider writing a method that returns the total profit as a double value. a) I b) II c) III d) I, II, and III

c) III

69) Which of the following options describes the process of stepwise refinement? I. Using arguments to pass information to a method II. Using unit tests to test the behavior of methods III. Decomposing complex tasks into simpler ones a) I b) II c) III d) I, II, and III

c) III

5) Parameter variables should not be changed within the body of a method because a) This will generate a compiler error b) This will generate a run-time error c) It is confusing because it mixes the concept of a parameter with that of a variable d) It is confusing because parameter variables cannot store values

c) It is confusing because it mixes the concept of a parameter with that of a variable

25) Which of the following is true about methods? a) Methods can have only one argument and can return only one return value. b) Methods can have multiple arguments and can return multiple return values. c) Methods can have multiple arguments and can return one return value. d) Methods can have one argument and can return multiple return values.

c) Methods can have multiple arguments and can return one return value.

89) For the given code snippet, which of the following statements is true? public static double raise(double rate) { double newPayRate = rate * 1.1; return newPayRate; } public static void main(String[] args) { double rate = 40.0; double newPayRate = 0.0; newPayRate = raise(rate); System.out.println("Pay rate: " + newPayRate); } a) The code snippet executes and displays "Pay rate: 40.0" b) The code snippet executes and displays "Pay rate: 44.0" c) The code snippet executes and displays "Pay rate: 0.0" d) There is no output because the program does not compile

b) The code snippet executes and displays "Pay rate: 44.0"

What is wrong with the following code? public static char grade(int score) { if (score >= 9) { return 'A'; } else if (score >= 8) { return 'B'; } else if (score >= 6) { return 'C'; } else if (score > 4) { return 'D'; } else if (score < 4) { return 'F'; } } a) Illegal parameter variable name b) Invalid parameter variable type c) No return statement for all logic paths d) Invalid argument in return statements Answer: c

c) No return statement for all logic paths

56) What is wrong with the following code? public static double div2(int n1, int n2) { if (n2 != 0) { return (double) n1 / n2; } } a) Compilation error b) Invalid parameter variable types c) No return statement for all possible logic paths d) Invalid return type

c) No return statement for all possible logic paths

57) What is wrong with the following code? public static char grade(int score) { if (score >= 9) { return 'A'; } else if (score >= 8) { return 'B'; } else if (score >= 6) { return 'C'; } else if (score >= 4) { return 'D'; } } a) Compilation error b) Invalid parameter variable types c) No return statement for all possible logic paths d) Invalid return type

c) No return statement for all possible logic paths

86) What is the output of the following code snippet? public static int assignPriority(int priority) { return priority + 2; } public static void main(String[] args) { int priority = assignPriority(3); System.out.println("Priority: " + priority); } a) Priority: 2 b) Priority: 3 c) Priority: 5 d) There is no output because the program does not compile

c) Priority: 5

100) Based on the code snippet below, which of the following statements is correct? public static void recursiveMethod(int count) { recursiveMethod(count + 2); System.out.println(count); } public static void main(String[] args) { recursiveMethod(1); } a) The code snippet gives a compilation error as the recursiveMethod method cannot call itself. b) The code snippet executes and infinitely recurses but does not print anything. c) The code snippet executes and displays 1. d) The code snippet executes and does not produce any output.

b) The code snippet executes and infinitely recurses but does not print anything.

60) Given the following code, what is the output? public static String magic(String s) { String r = ""; boolean got = false; for (int i = 0; i < s.length(); i++) { if (Character.isDigit(s.charAt(i))) { r = r + s.charAt(i); got = true; } else if (got) { return r; } } return r; } public static void main(String[] args) { System.out.println(magic("ABCd45&*31")); } a) ABCd b) 4531 c) 45&* d) 45

Answer: d 45

21. Which of the following statements about variables is true? a) The same variable name can be used in two different methods. b) The same name can be used for two different variables in a single method. c) You should use global variables whenever possible. d) A variable is visible from the point at which it is defined until the end of the program.

a) The same variable name can be used in two different methods.

2) The term "Black Box" is used with methods because a) Only the implementation matters; the specification is not important. b) Only the specification matters; the implementation is not important. c) Only the arguments matter; the return value is not important. d) Only the return value matters; the arguments are not important.

b) Only the specification matters; the implementation is not important.

80) What does the following code do? public static int getNumber(int number) { return (int) (Math.random() * number) + 1; } public static void main(String[] args) { for (int i = 1; i <= 10; i++) { System.out.println(getNumber(6) + " " + getNumber(6)); } } a) Generates any 10 random numbers b) Simulates the throwing of a pair of dice 10 times c) Generates 10 Fibonacci numbers d) Generates the same random number 20 times

b) Simulates the throwing of a pair of dice 10 times

1) Which process helps with identifying the methods that make up a computer program? a) Black boxing b) Stepwise refinement c) Parameter passing d) Debugging

b) Stepwise refinement

44) Which of the following options represents the output of the given code snippet? public static int addsub(int a, boolean isSub) { return (isSub ? sub(a) : a + 1); } public static int sub(int a) { return a - 1; } public static void main(String[] args) { System.out.println("Sub 5 = " + addsub(5, true) + ", Add 6 = " + addsub(6, false)); } a) Sub 5 = 6, Add 6 = 6 b) Sub 5 = 4, Add 6 = 7 c) Sub 5 = 6, Add 6 = 6 d) Sub 5 = 4, Add 6 = 6

b) Sub 5 = 4, Add 6 = 7

Given the following method, what method call will return true? public static boolean isValid(String input) { boolean valid = true; if (input.length() != 11) { valid = false; } else { if (input.charAt(3) != '-' || input.charAt(6) != '-') { valid = false; } else { valid = Character.isDigit(input.charAt(0)) && Character.isDigit(input.charAt(1)) && Character.isDigit(input.charAt(2)) && Character.isDigit(input.charAt(4)) && Character.isDigit(input.charAt(5)) && Character.isDigit(input.charAt(7)) && Character.isDigit(input.charAt(8)) && Character.isDigit(input.charAt(9)) && Character.isDigit(input.charAt(10)); } } return valid; } a) isValid("123-45-67") b) isValid("123-456789") c) isValid("123-45-6789") d) isValid("ABC-45-6789")

c) isValid("123-45-6789")

102) Which of the following method declarations would be appropriate for a method that compares 2 numbers? The method body is shown here: { return num1 > num2; } a) public static void compare(int num1, int num2) b) public static int compare(int num1, int num2) c) public static boolean compare(int num1, int num2) d) public static double compare(int num1, int num2)

c) public static boolean compare(int num1, int num2)

29) Which of the following is the correct header for a method definition named calcSum that accepts four int arguments and returns a double? a) public static double calcSum() b) public static calcSum(int a, int b, int c, int d) c) public static double calcSum(int a, int b, int c, int d) d) public static int calcSum(double a, double b, double c, double d)

c) public static double calcSum(int a, int b, int c, int d)

99) What is the output of the following code snippet? public static int someMethod(int x) { int result = 0; if (x > 10) { result = x; } else { result = someMethod(4 * x); } return result; } public static void main(String[] args) { System.out.println("someMethod(2) = " + someMethod(2)); } a) someMethod (2) = 8 b) someMethod (2) = 16 c) someMethod (2) = 32 d) someMethod (2) = 64

c) someMethod (2) = 32

18) What is the output from the following Java program? public class test03 { public static void main(String[] args) { for (int i = 0; i < 4; i++) { System.out.print(myFun(i) + " "); } System.out.println(); } public static int myFun(int perfect) { perfect = 0; return ((perfect - 1) * (perfect - 1)); } } a) -1 0 1 4 b) 1 0 1 4 c) 0 0 0 0 d) 1 1 1 1

d) 1 1 1 1

15) When hand-tracing methods, the values for the parameter variables a) Are the same each time the method is invoked b) Need not be traced because they are never returned c) May be undetermined or missing when the method executes d) Are determined by the arguments supplied in the code that invokes the method

d) Are determined by the arguments supplied in the code that invokes the method

37) What is the output of the following code snippet? public static void doubleAmount(int intvalue) { intvalue = 2 * intvalue; } public static void main(String[] args) { int principalAmt = 2000; System.out.println(doubleAmount(principalAmt)); } a) 2000 b) 4000 c) 0 d) Compilation error

d) Compilation error

19) Which line of code in the Java program below is the recursive invocation of method myFun? 1 public class test03 2 { 3 public static void main(String[] args) 4 { 5 for (int i = 0; i < 4; i++) 6 { 7 System.out.print(myFun(i) + " "); 8 } 9 System.out.println(); 10 } 11 public static int myFun(int perfect) 12 { 13 return ((perfect - 1) * (perfect - 1)); 14 } 15 } a) 7 b) 11 c) 13 d) There is no recursive invocation

d) There is no recursive invocation

8) Which statement about the steps for implementing a method is true? a) Pseudocode is the first step in the process for implementing a method b) Pseudocode is the last step in the process for implementing a method c) Unit testing (testing in isolation) of the implemented method is an important first step d) Unit testing (testing in isolation) of the implemented method is an important final step

d) Unit testing (testing in isolation) of the implemented method is an important final step

42) Which of the following options represents the output of the code snippet below? public static void doIt(int a, int prv, int nxt) { prv = a - 1; nxt = a + 1; } public static void main(String[] args) { int a = 100; int b = 100; int c = 100; doIt(a, b, c); System.out.println("b = " + b + ", c = " + c); } a) b = 100, c = 101 b) b = 99, c = 100 c) b = 99, c = 101 d) b = 100, c = 100

d) b = 100, c = 100

84) Given the following method, what do we need to fix? public static String getPerformance(char grade) { switch (grade) { case 'A': return "Excellent"; break; case 'B': return "Good"; break; case 'C': return "Mediocre"; break; case 'D': return "Weak"; break; case 'F': return "Bad"; break; } } a) Remove all the break statements b) Add a local boolean variable definition c) Remove all the break statements and add a return statement before the end of method d) Remove the switch statement and use and if statement

c) Remove all the break statements and add a return statement before the end of method

62) Which of the following is the best choice for a return type from a method that prompts users to enter their credit card number exactly as it appears on the card? a) boolean b) int c) String d) long

c) String

65) Which of the following is the best choice for a return type from a method that prompts users to enter their password? a) char b) int c) String d) void

c) String

81) Which of the following options represents the output of the given code snippet? public static int addsub(int a, boolean isSub) { if (isSub) { return sub(a); } else {return a + 1; } } public static int sub(int a) { return a - 1; } public static void main(String[] args) { System.out.println("Sub 5 = " + addsub(5, false) + ", Add 6 = " + addsub(6, true)); } a) Sub 5 = 6, Add 6 = 6 b) Sub 5 = 4, Add 6 = 7 c) Sub 5 = 6, Add 6 = 5 d) Sub 5 = 4, Add 6 = 6

c) Sub 5 = 6, Add 6 = 5

51) What step should you take after implementing a method? a) Write the pseudocode. b) Determine the parameter variables. c) Test the method in isolation. d) Define the scope of the method.

c) Test the method in isolation.

10) What is the problem with the code snippet below? public class test02 { public static void main(String[] args) { System.out.println(cost(10, 4)); } public static void cost(int price, int reps) { for (int i = 0; i < reps; i++) { System.out.print(price); } return; } } a) The method cost is invoked with the wrong arguments b) The method cost uses uninitialized variables c) The method cost returns void and cannot be used as an expression in a print statement d) The method cost must return an integer value

c) The method cost returns void and cannot be used as an expression in a print statement

72) What is a good rule for deciding the number of statements in a method? a) It is fine to put as many statements in the method as possible. b) The method should perform multiple tasks and contain multiple statements. c) The method should perform only one task and contain just enough statements for the task. d) The method should contain no more than 3 statements.

c) The method should perform only one task and contain just enough statements for the task.

11) If a method is declared to return void, then which statement below is true? a) The method cannot return until reaching the end of the method body b) The method needs a return statement that always returns the integer value zero c) When the method terminates no value will be returned d) The method cannot be invoked unless it is in an assignment statement

c) When the method terminates no value will be returned

82) For a program that reads three letter grades and calculates an average of those grades, which of the following would be a good design based on stepwise refinement? a) Write one method that reads three letter grades, converts each letter grade to a number, and calculates the average of the three numbers. b) Write one method that reads three letter grades, and a second method to convert each letter to a number and calculate the average of the three numbers. c) Write one method that reads a letter grade and returns the number equivalent, and one method that computes the average of three numbers. d) Stepwise refinement cannot be applied to this problem.

c) Write one method that reads a letter grade and returns the number equivalent, and one method that computes the average of three numbers.

68) For a program that reads city names repeatedly from the user and calculates the distance from a company's headquarters, which of the following would be a good design based on stepwise refinement? a) Write one method that calculates distance randomly. b) Write one method that reads city name. c) Write one method that reads city name and another method that calculates distance. d) Write one method that reads distance and finds city name.

c) Write one method that reads city name and another method that calculates distance.

90) What is the output of the following code snippet? public static int doIt(int a, int prv1, int nxt1) { int prv = a - prv1; int nxt = a + nxt1; return prv; } public static void main(String[] args) { int a = 100; int b = 100; int c = 100; b = doIt(a, b, c); System.out.println("b = " + b + ", c = " + c); } a) b = 100, c = 101 b) b = 99, c = 101 c) b = 0, c = 100 d) b = 0, c = 101

c) b = 0, c = 100

66) What is incorrect in the following code snippet? public static void displayBox(String str) { System.out.println("--------"); System.out.println(str); System.out.println("--------"); } public static void main(String[] args) { System.out.println(displayBox("Hello World")); } a) displayBox is called with incorrect arguments. b) displayBox should be called in an assignment statement. c) The return value from displayBox is never used. d) displayBox does not return a value; therefore, it cannot be used with System.out.println

d) displayBox does not return a value; therefore, it cannot be used with System.out.println

53) You need to write a method that calculates the shipping cost for an appliance, which depends on the item's 3D dimensions and weight. What should be the inputs and their data types for this method? a) double size, double weight b) double size, double weight, double price c) double size, double weight, double shippingCost d) double width, double height, double depth, double weight

d) double width, double height, double depth, double weight

47) You need to write a method that calculates the volume for a shape, which depends on the shape's length, width, and height. What should be the parameter variables and their data types for this method? a) double length, double height b) double length c) double length, double height, String depth d) double width, double length, double height

d) double width, double length, double height

96) Which of the following code snippets returns the factorial of a given number? (Hint: Factorial of 5 = 5! = 1 * 2 * 3 * 4 * 5 = 120) a) public static int factorial(int num) { return num * factorial(num - 1); } b) public static int factorial(int num) { if (num == 1) { return 1; } return num * factorial(num); } c) public static int factorial(int num) { if (num == 1) { return 1; } System.out.println(num * factorial(num - 1)); } d) public static int factorial(int num) { if (num == 1) { return 1; } return num * factorial(num - 1); }

d) public static int factorial(int num) { if (num == 1) { return 1; } return num * factorial(num - 1); }

63) What is incorrect in the following code snippet? public static void textInRectangle(String str) { System.out.println("--------"); System.out.println("|" + str + "|"); System.out.println("--------"); } public static void main(String[] args) { System.out.println(textInRectangle("Hello there"); } a) textInRectangle is called with incorrect arguments. b) textInRectangle should be called in an assignment statement. c) The return value from textInRectangle is never used. d) textInRectangle does not return a value; therefore, it cannot be used with System.out.println

d) textInRectangle does not return a value; therefore, it cannot be used with System.out.println

74) Assuming that a user enters 45 as the brightness of a lamp, which of the following hand trace tables is valid for the code below? public static void main(String[] args) { int brightness = 0; Scanner in = new Scanner(System.in); System.out.print( "Please enter your lamp brightness (in watts): "); brightness = in.nextInt(); System.out.println("Lamp is " + getDescription(brightness)); } public static String getDescription(int brightness) { String description = ""; if (brightness >= 120) { description = "very bright"; if (brightness >= 100) { description = "bright"; } } else { description = "pleasant"; if (brightness <= 50) { description = "dim"; } } return description; } a) Brightness Description 0 "" 45 "pleasant" "dim" b) Brightness Description 0 "very bright" 45 "bright" c) Brightness Description 0 "" 45 "bright" "pleasant" d) Brightness Description 0 "bright" 45 "pleasant"

a) Brightness Description 0 "" 45 "pleasant" "dim"

73) Assuming that a user enters 22 as the price of an item, which of the following hand trace tables is valid for the code below? public static void main(String[] args) { int price = 0; Scanner in = new Scanner(System.in); System.out.print("Please enter object's price: "); price = in.nextInt(); System.out.println("Object price is " + getStatus(price)); } public static String getStatus(int price) { String status = ""; if (price >= 50) { status = "reasonable"; if (price >= 75) { status = "costly"; } } else { status = "inexpensive"; if (price <= 25) { status = "reasonable"; } } return status; } a) Price Status 0 "" 22 "inexpensive" "reasonable" b) Price Status 0 "inexpensive" 22 "reasonable" c) Price Status 0 "" 22 "reasonable" "costly" d) Price Status 0 "reasonable" 22 "costly"

a) Price Status 0 "" 22 "inexpensive" "reasonable"

94) What is the output if the method call is testMyVal(6) in the following code snippet? public static void testMyVal(int nval) { if (nval > 0) { testMyVal(nval - 2); } System.out.print(nval + " "); } a) 0 2 4 6 b) 0 0 0 0 c) 6 6 6 6 d) 6 4 2 0

a) 0 2 4 6

101) Given the code below, what is the output of the method call hashIt("#", 6)? public static void hashIt(String s, int d) { if (d <= 1) { System.out.print(d); } else { s = s + "/"; hashIt(s, d - 2); System.out.print(s + d); } } a) 0#///2#//4#/6 b) 0#/2#//4#///6 c) 0/2#//4#///6# d) #/6#//4#///20

a) 0#///2#//4#/6

26) What is the output of the following code snippet? public static int recurrAverage(int num) { int sum = 0; for (int x = 1; x <= num; x++) { sum = sum + x; } return sum / num; } public static void main(String[] args) { System.out.println(recurrAverage(recurrAverage(16))); } a) 4 b) 8 c) 12 d) 16

a) 4

48) Which of the following is true about method return statements? a) A method can hold multiple return statements, but only one return statement executes in one method call. b) A method can hold only one return statement. c) A method can hold multiple return statements, and multiple return statements can execute in one method call. d) A method can have maximum of two return statements.

a) A method can hold multiple return statements, but only one return statement executes in one method call.

85) In the following code snippet, what is the scope of variable b? public static void m1() { int i = 0; double b = 0; } public static void m2() { double a = b + 1; } public static void main(String[] args) { m1(); m2(); } a) It can be used only in m1. b) It can be used in user-defined methods m1 and m2. c) It can be used anywhere in this program. d) It can be used in many programs.

a) It can be used only in m1.

14) Why is hand-tracing, or manually walking through the execution of a method, helpful? a) It is an effective way to understand a method's subtle aspects b) It guarantees that the method will compile without errors c) It makes unit testing unnecessary d) It enforces the "black-box" concept of method design

a) It is an effective way to understand a method's subtle aspects

83) An effective technique for understanding the subtle aspects of a method is to: a) Perform a manual walkthrough. b) Write stub methods. c) Use the Java compiler to catch compile-time errors. d) Write large methods to eliminate the run-time overhead of calling methods.

a) Perform a manual walkthrough.

20) Which of the following is NOT a good practice when developing a computer program? a) Put as many statements as possible into the main method b) Document the purpose of each method parameter c) Decompose a program into many small methods d) Place code that is used multiple times into a separate method

a) Put as many statements as possible into the main method

4) After the keywords "public static", what are the names (in order) of the parts of this method header? public static int myFun (double a) a) Return type, method name, parameter variable type, parameter variable name b) Return type, method name, parameter variable name, parameter variable type c) Method name, method type, parameter variable type, parameter variable name d) Method name, method type, parameter variable name, parameter variable type

a) Return type, method name, parameter variable type, parameter variable name

71) A temporary method that is used to provide a quick way to test other methods is called: a) Stub b) Parameter c) Caller d) Assessor

a) Stub

23) The Math.ceil method in the Java standard library takes a single value x and returns the smallest integer that is greater than or equal to x. Which of the following is true about Math.ceil(56.75)? a) The argument is 56.75, and the return value is 57. b) The argument is 56.75, and the return value is 56. c) The argument is 57, and the return value is 56.75. d) The argument is 56, and the return value is 56.75.

a) The argument is 56.75, and the return value is 57.

30) What is the error in the following method definition? public static int tripler(int numPara) { double result = numPara * 3; } a) The method does not return a value. b) The method returns a value of type double. c) The method does not modify its parameter variable. d) The method should be private.

a) The method does not return a value.

9) What is the problem with the code snippet below? public static String val() { String result = "candy"; return; } . . . // Using method val() System.out.println("The value is: " + val()); a) The method val does not have a return value. b) The method val does not have any parameter variables. c) The use of val in the System.out.println statement is illegal. d) The String data type cannot be returned from a method.

a) The method val does not have a return value.

17) The variable name perfect in the method myFun in the code snippet below is used as both a parameter variable and a variable in a nested block within the method. Which statement about this situation is true? public static int myFun(int perfect) { { int perfect = 0; return ((perfect - 1) * (perfect - 1)); } } a) This multiple declaration of the variable perfect will not compile because the scopes overlap b) While this is legal and will compile in Java, it is confusing c) Because the scopes of these variables do not overlap, there is no problem d) This situation rarely occurs and the compiler always issues a warning

a) This multiple declaration of the variable perfect will not compile because the scopes overlap

70) What is the purpose of writing a stub method? a) To test another method without writing all the implementation details of a method called by the method being tested b) To provide a simpler implementation of a complex method c) To run a unit test for another method d) To call a method that is being developed

a) To test another method without writing all the implementation details of a method called by the method being tested

3) One advantage of designing methods as black boxes is that a) many programmers can work on the same project without knowing the internal implementation details of methods. b) the result that is returned from black-box methods is always the same data type. c) the implementation of the method is open for everyone to see. d) there are fewer parameters.

a) many programmers can work on the same project without knowing the internal implementation details of methods.

41) What are the values of x and y after executing the code snippet below? public static void swap(int a, int b) { int t = a; a = b; b = t; } public static void main(String[] args) { int x = 10; int y = 11; swap(x, y); } a) x = 10 and y = 11 b) x = 11 and y = 10 c) x = 0 and y = 0 d) x = 11 and y = 11

a) x = 10 and y = 11

6) What is the output of the following Java program? public class test01 { public static void main(String[] args) { for (int i = 0; i < 4; i++) { System.out.print(myFun(i) + " "); } } public static int myFun(int perfect) { return ((perfect - 1) * (perfect - 1)); } } a) -1 0 1 4 b) 1 0 1 4 c) -1 0 1 4 9 d) 1 4 9 16

b) 1 0 1 4

97) Given the method below, what is the result of the method call recstr("#", 5)? public static void recstr(String s, int d) { if (d <= 1) { System.out.print (d); } else { s = s + "/"; recstr(s, d - 2); System.out.print (s + d); } } a) 1//#3/#5 b) 1#//3#/5 c) 1##/#/5 d) 0##/#/5

b) 1#//3#/5

Which of the following code snippets can be used for defining a method that does not return a value? The method should accept a string and then display the string followed by "Just Let's learn Java!" on a separate line. a) public static String showString(String someString) { System.out.println(someString); System.out.println("Just Let's learn Java!"); } b) public static void showString(String someString) { System.out.println(someString); System.out.println("Just Let's learn Java!"); } c) public static void showString(String someString) { System.out.println(someString); System.out.println("Just Let's learn Java!"); return someString; } d) public static void showString() { System.out.println(someString); System.out.println("Just Let's learn Java!"); }

b) public static void showString(String someString) { System.out.println(someString); System.out.println("Just Let's learn Java!"); }

95) Given the method below, what is the output of the method call is div(10)? public static void div(int n) { if (n > 2) { div(n % 3); } System.out.print(n / 3 + " "); } a) 0 10 b) 3 c) 0 3 d) 10

c) 0 3

32) What is the output of the following code snippet? public class test04 { public static int pow(int base, int power) { int result = 1; for (int i = 0; i < power; i++) { result = result * base; } return result; } public static void main(String[] args) { System.out.println(pow(pow(2, 2), 2)); } } a) 4 b) 8 c) 16 d) 32

c) 16

91) What is the output of the following code snippet? public static int blackBox(int a) { int val; if (a <= 0) { val = 1; } else { val = a + blackBox(a - 2); } return val; } public static void main(String[] args) { System.out.println(blackBox(4)); } a) 4 b) 1 c) 7 d) 2

c) 7

61) Given the following code, what is the output? public class MysteriousClass { public static void main(String[] args) { int i = 20; int b = m2(i); System.out.println(b + i); } public static int m1(int i) { int n = 0; while (n * n <= i) { n++; } return n - 1; } public static int m2(int a) { int b = 0; for (int n = 0; n < a; n++) { int i = m1(n); b = b + i; } return b; } } a) 50 b) 60 c) 70 d) 80

c) 70

16) A stub method is a) A short method b) A method that has been unit tested c) A method that acts as a placeholder and returns a simple value so another method can be tested d) A method that is broken down into smaller steps through step-wise refinement

c) A method that acts as a placeholder and returns a simple value so another method can be tested

76) Given the following method that checks for a valid 5-digit number, what do we need to fix? public static boolean isValid(String s) { if (s != null && s.length() == 5) { int i = 0; boolean b = Character.isDigit(s.charAt(i)) && Character.isDigit(s.charAt(i + 1) && Character.isDigit(s.charAt(i + 2)) && Character.isDigit(s.charAt(i + 3)) && Character.isLetter(s.charAt(i + 4)); } else { return false; } } a) Change the parameter variable type to integer b) Add another local Boolean variable definition c) Add a return statement inside the "if" branch d) Add a new Boolean parameter variable

c) Add a return statement inside the "if" branch

36) Consider this method comment. Which of the following options is recommended in your textbook? /** Computes the area of a cuboid. @param width the width of the cuboid @return the area of the cuboid */ public static double area(double width, double height, double length) { double result = width * height * length; return result; } a) The parameter "width" need not be described. b) The first line of the comment should be omitted because it is obvious. c) All of the parameters should be described. d) The @return clause of the comment should be omitted because it is obvious.

c) All of the parameters should be described.

78) Given the following method, what is the result of getNumber(n)? public static double getNumber(double n) { return Math.pow(Math.sqrt(n), 2) - n; } a) Always 0 for every argument n b) Always 2 for every argument n c) Close to 0, but not always 0 d) Compilation error

c) Close to 0, but not always 0

28) In a vehicle mileage application, you enter number of miles traveled by a vehicle and the amount of fuel used for 30 consecutive days. From this data the average monthly mileage of the vehicle is calculated. Which of the following should be done to improve the program design? a) The next time the average monthly mileage is calculated, use copy and paste to avoid making coding errors. b) Provide the same comment every time you repeat the average monthly mileage calculation. c) Consider writing a method that returns the average monthly mileage as a double value. d) Consider writing a method that returns void

c) Consider writing a method that returns the average monthly mileage as a double value.

49) A programmer notices that the following code snippet uses the same algorithm for computing cost after taxes, but with different variables, in the two places as shown below, and in several other places in the program. What could be done to improve the program? final double TAXRATE1 = 10; final double TAXRATE2 = 5.5; double subtotal = price * (1 + TAXRATE1) / 100; double total = subtotal + shipping * (1 + TAXRATE2) / 100; a) Declare the tax rates as variables, not constants. b) Define a method that looks up tax rates for goods and shipping charges. c) Define a method that prompts the user for an amount and a tax rate, then returns the total amount including the tax. d) Define a method that computes the cost after taxes from arguments for the cost before taxes and the tax rate.

d) Define a method that computes the cost after taxes from arguments for the cost before taxes and the tax rate.

46) A programmer notices that the following code snippet uses the same algorithm for computing interest earned, but with different variables, in the two places shown below and in several other places in the program. What could be done to improve the program? final double RATE1 = 10; final double RATE2 = 5.5; double interest = investment * RATE1 / 100; . . . balance = balance + balance * RATE2 / 100; a) Declare the rates as variables, not constants. b) Define a method that looks up interest rates. c) Define a method that prompts the user for an amount and a rate of interest, then returns the interest earned. d) Define a method that computes the interest earned from an amount and a rate of interest.

d) Define a method that computes the interest earned from an amount and a rate of interest.

54) Given the following code, which argument(s) will cause the method to return true? public static boolean isIdeal(String s) { int low = 0; int high = s.length() - 1; while (low < high) { if (s.charAt(low) != s.charAt(high)) { return false; } low++; high--; } return true; } I. isIdeal("civic") II. isIdeal("level") III. isIdeal("race car") IV. isIdeal("rotor") a) I only b) I and II only c) I, II, and III d) I, II, and IV

d) I, II, and IV

55) Given the following code, which method call(s) will cause the method to return true? public static boolean isIdeal(int year) { return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } I. isIdeal(1600) II. isIdeal(1700) III. isIdeal(2000) IV. isIdeal(2008) a) I only b) I and II only c) I, II, and III d) I, III, and IV

d) I, III, and IV

58) What is wrong with the following code? public static String grade(int score) { if (score >= 9) { return A; } else if (score >= 8) { return B; } else if (score >= 6) { return C; } else if (score >= 4) { return D; } return F; } a) Illegal method name b) Invalid parameter variable type c) No return statement for all branches of "if" statement d) Invalid argument in return statements

d) Invalid argument in return statements

59) What is wrong with the following code? public static int count(String s) { for (int i = 0; i < s.length(); i++) { int cnt = 0; if (Character.isDigit(s.charAt(i))) { cnt++; } } return cnt; } a) Illegal return type b) Invalid parameter variable type c) No return statement d) Invalid scope of variable used in return statement

d) Invalid scope of variable used in return statement

87) Which of the following is correct about a local variable? a) It is declared before all the methods in a program. b) It is visible to all the methods declared after it. c) It is declared exclusively in the main method. d) It is declared within the scope of any method.

d) It is declared within the scope of any method.

77) Given the following method, what do we need to fix? public static String getPerformance(char grade) { if (grade == 'A' || grade == 'B' || grade == 'C' || grade == 'D' || grade == 'F') { String desc = ""; switch (grade) { case 'A': desc = "Excellent"; break; case 'B': desc = "Good"; break; case 'C': desc = "Mediocre"; break; case 'D': desc = "Weak"; break; case 'F': desc = "Bad"; break; } } return desc; } a) Change the parameter variable type to String b) Add a local Boolean variable definition to test the input c) Add return statements inside the switch branches d) Move the definition of the local variable desc before the if statement

d) Move the definition of the local variable desc before the if statement

22) Which of the following is not legal in a method definition? a) Multiple parameter variables b) Parameter variable data types c) One return value d) Multiple return values

d) Multiple return values

88) What is the output of the following code snippet? public static void main(String[] args) { int gvar = 0; gvar = gvar + 10; if (gvar > 0) { int lvar = gvar + 1; } System.out.println(lvar); } a) 1 b) 10 c) 11 d) No output due to compilation error

d) No output due to compilation error

45) What is the output of the given code snippet? public static int addsub(int a, int sub, int add) { sub = a - 1; return sub; add = a + 1; return add; } public static void main(String[] args) { int a = 5; int b = 0; int c = 0; addsub(a, b, c); System.out.println("Subtract = " + b + ", Add = " + c); } a) Subtract = 6, Add = 6 b) Subtract = 4, Add = 5 c) Subtract = 4, Add = 0 d) No output, compilation error

d) No output, compilation error

7) Which option represents a legal invocation of the method square()? public static String square(int a) { return ("Commencing"); } a) int a = square(4); b) String a = square("help"); c) double a = square(4.0); d) String a = square(4);

d) String a = square(4);

52) What is the problem with the definition of the following method that calculates and returns the tax due on a purchase amount? public static double taxDue(double amount, double taxRate) { double taxDue = 0.0; taxDue = amount * taxRate; } a) The taxDue method should not be static. b) The data type of the parameter variables is incorrect. c) The taxDue calculation is incorrect. d) The taxDue method does not return a value.

d) The taxDue method does not return a value.

35) What is the syntax error in the following method definition? public static String parameter(double r) { double result; result = 2 * 3.14 * r; return result; } a) The method does not return the value result. b) The method does not specify the result return type. c) The variable result is set but never used. d) The value that is returned does not match the specified return type.

d) The value that is returned does not match the specified return type.


Kaugnay na mga set ng pag-aaral

Chapter 6 Adaptations to Aerobic Training

View Set

Management (11th ed) - Chapter 2 - Griffin

View Set

Ch. 25 Assessment of Respiratory System - TB

View Set

Patient Assessment (tiburzi) Neuro

View Set

Chapter 16 - Supporting mobile operating systems

View Set

8 - Social Security (xcel solutions)

View Set

Post-test: Electrical SystemsQuiz

View Set

2 Una día típico: Spanish 1 Unit 4

View Set