Comp Sci Final
Consider the following methods, which appear in the same class. public void slope(int x1, int y1, int x2, int y2) { int xChange = x2 - x1; int yChange = y2 - y1; printFraction(yChange, xChange); } public void printFraction(int numerator, int denominator) { System.out.print(numerator + "/" + denominator); } Assume that the method call slope(1, 2, 5, 10) appears in a method in the same class. What is printed as a result of the method call?
8/4
Consider the following class definition. public class ExamScore { private String studentId; private double score; public ExamScore(String sid, double s) { studentId = sid; score = s; } public double getScore() { return score; } public void bonus(int b) { score += score * b/100.0; } } Assume that the following code segment appears in a class other than ExamScore. ExamScore es = new ExamScore("12345", 80.0); es.bonus(5); System.out.println(es.getScore()); What is printed as a result of executing the code segment?
84.0
The code segment below is intended to print the length of the shortest string in the array wordArray. Assume that wordArray contains at least one element. int shortest = /* missing value */; for (String word : wordArray) { if (word.length() < shortest) { shortest = word.length(); } } System.out.println(shortest); Which of the following should be used as the initial value assigned to shortest so that the code segment works as intended?
Integer.MAX_VALUE
Consider the following code segment, where letters is a two-dimensional (2D) array that contains possible letters. The code segment is intended to print "DIG". String[][] letters = {{"A", "B", "C"}, {"D", "E", "F"}, {"G", "H", "I"}}; System.out.println( /* missing code */ ); Which of the following could replace /* missing code */ so that the code segment works as intended?
letters[1][0] + letters[2][2] + letters[2][0]
Consider the following method, which is intended to return an array of integers that contains the elements of the parameter arr arranged in reverse order. For example, if arr contains {7, 2, 3, -5}, then a new array containing {-5, 3, 2, 7} should be returned and the parameter arr should be left unchanged. public static int[] reverse(int[] arr) { int[] newArr = new int[arr.length]; for (int k = 0; k < arr.length; k++) { /* missing statement */ } return newArr; } Which of the following statements can be used to replace /* missing statement */ so that the method works as intended?
newArray[k] = arr[arr.length - k - 1];
The Car class will contain two string attributes for a car's make and model. The class will also contain a constructor. public class Car { /* missing code */ } Which of the following replacements for /* missing code */ is the most appropriate implementation of the class?
private String make; private String model; public Car(String myMake, String myModel) { /* implementation not shown */ }
public static void addOneToEverything(int[] numbers) { for (int j = 0; j < numbers.length; j++) { numbers[j]++; } } Which of the following code segments, if any, can be used to replace the body of the method so that numbers will contain the same values? I. for (int num : numbers) { num++; } II. for (int num : numbers) { num[j]++; } III. for (int num : numbers) { numbers[num]++; }
None of the code segments will return an equivalent result.
Consider the following methods, which appear in the same class. public void printSum(int x, double y) { System.out.println(x + y); } public void printProduct(double x, int y) { System.out.println(x * y); } Consider the following code segment, which appears in a method in the same class as printSum and printProduct. int num1 = 5; double num2 = 10.0; printSum(num1, num2); printProduct(num1, num2); What, if anything, is printed as a result of executing the code segment?
Nothing is printed because the code does not compile.
Consider the definition of the Person class below. The class uses the instance variable adult to indicate whether a person is an adult or not. public class Person { private String name; private int age; private boolean adult; public Person (String n, int a) { name = n; age = a; if (age >= 18) { adult = true; } else { adult = false; } } } Which of the following statements will create a Person object that represents an adult person?
Person p = new Person ("Homer", 23);
Consider the following method. public int[] addNum(int[] array, int first, int second, int num) { int[] newArray = new int[array.length]; newArray[first] = array[first] + num; newArray[second] = array[second] + num; return newArray; } Which of the following code segments, appearing in the same class as the addNum method, will result in array2 having the contents {0, 0, 13, 0, 9, 0, 0} ?
int[] array1 = {5, 2, 8, 6, 4, 3, 9}; int[] array2 = addNum(array1, 2, 4, 5);
Consider the following code segment, where nums is a two-dimensional (2D) array of integers. The code segment is intended to print "test1234". System.out.print("test" + nums[0][0] + nums[1][0] + nums[1][1] + nums[0][1]); Which of the following code segments properly declares and initializes nums so that the code segment works as intended? Responses A int[][] nums = {{1, 2}, {3, 4}}; B int[][] nums = {{1, 2}, {4, 3}}; C int[][] nums = {{1, 3}, {2, 4}}; D int[][] nums = {{1, 4}, {2, 3}}; E int[][] nums = {{1, 4}, {3, 2}};
int[][] nums = {{1, 4}, {2, 3}};
The following method is intended to return true if and only if the parameter val is a multiple of 4 but is not a multiple of 100 unless it is also a multiple of 400. The method does not always work correctly. public boolean isLeapYear(int val) { if ((val % 4) == 0) { return true; } else { return (val % 400) == 0; } } Which of the following method calls will return an incorrect response?
isLeapYear(1900)
Consider the following code segment, where num is a properly declared and initialized integer variable. The code segment is intended to traverse a two-dimensional (2D) array arr looking for a value equal to num and then print the value. The code segment does not work as intended. int[][] arr = {{7, 3, 6, 4}, {9, 2, 0, 5}, {1, 4, 3, 8}}; for (int j = 0; j < arr.length - 1; j++) { for (int k = 0; k < arr[0].length; k++) { if (arr[j][k] == num) { System.out.println(arr[j][k]); } } } For which of the following values of num does the code segment not work as intended?
num = 8
Consider the following method, which is intended to return the product of 3 and the nonnegative difference between its two int parameters. public int threeTimesDiff (int num1, int num2) { return 3 * (num1 - num2); } Which, if any, precondition is required so that the method works as intended for all values of the parameters that satisfy the precondition?
num1 >= num2
A student has created an OrderedPair class to represent points on an ��-plane. The class contains the following. An int variable called x to represent an �-coordinate. An int variable called y to represent a �-coordinate. A method called printXY that will print the values of x and y. The object origin will be declared as type OrderedPair. Which of the following descriptions is accurate?
origin is an instance of the OrderedPair class.
The Date class below will contain three int attributes for day, month, and year, a constructor, and a setDate method. The setDate method is intended to be accessed outside the class. public class Date { /* missing code */ } Which of the following replacements for /* missing code */ is the most appropriate implementation of the class?
private int day; private int month; private int year; public Date() { /* implementation not shown */ } public void setDate(int d, int m, int y) { /* implementation not shown */ }
Consider the following class definition. public class Tester { private int num1; private int num2; /* missing constructor */ } The following statement appears in a method in a class other than Tester. It is intended to create a new Tester object t with its attributes set to 10 and 20. Tester t = new Tester(10, 20); Which of the following can be used to replace /* missing constructor */ so that the object t is correctly created?
public Tester(int first, int second) { num1 = first; num2 = second; }
Consider the following code segment. int count = 5; while (count < 100) { count = count * 2; } count = count + 1; What will be the value of count as a result of executing the code segment?
161
Consider the following code segment. String str1 = new String("Advanced Placement"); String str2 = new String("Advanced Placement"); if (str1.equals(str2) && str1 == str2) { System.out.println("A"); } else if (str1.equals(str2) && str1 != str2) { System.out.println("B"); } else if (!str1.equals(str2) && str1 == str2) { System.out.println("C"); } else if (!str1.equals(str2) && str1 != str2) { System.out.println("D"); } What, if anything, is printed when the code segment is executed?
B
Consider the following Point2D class. public class Point2D { private double xCoord; private double yCoord; public Point2D(double x, double y) { xCoord = x; yCoord = y; } } Which of the following code segments, appearing in a class other than Point2D, will correctly create an instance of a Point2D object?
Point2D p = new Point2D(3.0, 4.0);
The twoInARow method below is intended to return true if any two consecutive elements of the parameter arr are equal in value and return false otherwise. public boolean twoInARow(int[] arr) { /* missing loop header */ { if (arr[k] == arr[k + 1]) { return true; } } return false; } Which of the following can be used to replace /* missing loop header */ so that the method will work as intended?
for (int k = 0; k < arr.length - 1; k++)
The Player class below will contain two int attributes and a constructor. The class will also contain a method getScore that can be accessed from outside the class. public class Player { /* missing code */ } Which of the following replacements for /* missing code */ is the most appropriate implementation of the class?
private int score; private int id; public Player(int playerScore, int playerID) { /* implementation not shown */ } public int getScore() { /* implementation not shown */ }
if (randomNumber <= 0.70) { event = 1; } if (randomNumber <= 0.80) { event = 2; } else { event = 3; } The code does not work as intended. Assume that the variable randomNumber has been properly declared and initialized. Which of the following initializations for randomNumber will demonstrate that the code segment will not work as intended?
randomNumber = 0.70;
Consider the following code segment. int a = 4; int b = 5; a++; b++; int c = a + b; a -= 1; System.out.println(a + c); What is printed when the code segment is executed?
15
Consider the following code segment. int x = 5; x += 6 * 2; x -= 3 / 2; What value is stored in x after the code segment executes?
16
Consider the following code segment, which is intended to assign to num a random integer value between min and max, inclusive. Assume that min and max are integer variables and that the value of max is greater than the value of min. double rn = Math.random(); int num = /* missing code */; Which of the following could be used to replace /* missing code */ so that the code segment works as intended?
(int) (rn * (max - min + 1)) + min
The following method is intended to return a string containing the character at position n in the string str. For example, getChar("ABCDE", 2) should return "C". /* missing precondition */ public String getChar(String str, int n) { return str.substring(n, n + 1); } Which of the following is the most appropriate precondition for the method so that it does not throw an exception? Responses
/* Precondition: 0 <= n <= str.length() - 1 */
Consider the following code segment. double regularPrice = 100; boolean onClearance = true; boolean hasCoupon = false; double finalPrice = regularPrice; if(onClearance) { finalPrice -= finalPrice * 0.25; } if(hasCoupon) { finalPrice -= 5.0; } System.out.println(finalPrice); What is printed as a result of executing the code segment?
75.0
Consider the following code segment. double x = 4.5; int y = (int) x * 2; System.out.print(y); What is printed as a result of executing the code segment?
8
Consider the following code segment. int a = 5; int b = 4; int c = 2; a *= 3; b += a; b /= c; System.out.print(b); What is printed when the code segment is executed?
9
Consider the following code segment. int a = 5; int b = 8; int c = 3; System.out.println(a + b / c * 2); What is printed as a result of executing this code? Responses
9
Consider the following code segment. int num = 1; while (num < 5) { System.out.print("A"); num += 2; } What is printed as a result of executing the code segment?
AA
A student has created a Car class. The class contains variables to represent the following. A String variable called color to represent the color of the car An int variable called year to represent the year the car was made A String variable called make to represent the manufacturer of the car A String variable called model to represent the model of the car The object vehicle will be declared as type Car. Which of the following descriptions is accurate?
An attribute of the vehicle object is color.
public class Computer { private String memory; public Computer() { memory = "RAM"; } public Computer(String m) { memory = m; } public String getMemory() { return memory; } } public class Smartphone extends Computer { private double screenWidth, screenHeight; public SmartPhone(double w, double h) { super("flash"); screenWidth = w; screenHeight = h; } public double getScreenWidth() { return screenWidth; } public double getScreenHeight() { return screenHeight; } } The following code segment appears in a class other than Computer or Smartphone. (code...) The code segment is intended to produce the following output. Device has memory: flash, screen area: 11.5515 square inches. Which of the following best explains why the code segment does not work as intended?
An error occurs during compilation because the getScreenWidth and getScreenHeight methods are not defined for the Computer object myPhone.
Consider the following class definition. public class Element { public static int max_value = 0; private int value; public Element (int v) { value = v; if (value > max_value) { max_value = value; } } } The following code segment appears in a class other than Element. for (int i = 0; i < 5; i++) { int k = (int) (Math.random() * 10 + 1); if (k >= Element.max_value) { Element e = new Element(k); } } Which of the following best describes the behavior of the code segment?
Between 1 and 5 Element objects are created, and Element.max_value is increased for at least one object created.
Consider the following code segment. int w = 1; int x = w / 2; double y = 3; int z = (int) (x + y); Which of the following best describes the results of compiling the code segment?
The code segment compiles without error.
Consider the following code segment. num += num; num *= num; Assume that num has been previously declared and initialized to contain an integer value. Which of the following best describes the behavior of the code segment? Responses
The value of num is the square of twice its original value.
Consider the following class definition. public class WordClass { private final String word; private static String max_word = ""; public WordClass (String s) { word = s; if (word.length() > max_word.length()) { max_word = word; } } } Which of the following is a true statement about the behavior of WordClass objects?
Every time a WordClass object is created, the max_word variable is referenced.
Consider the following Boolean expressions. I. A && B II. !A && !B Which of the following best describes the relationship between values produced by expression I and expression II?
Expression I and expression II evaluate to the same value only when A and B differ.
Consider the following code segment. String[][] arr = {{"Hello,", "Hi,", "Hey,"}, {"it's", "it is", "it really is"}, {"nice", "great", "a pleasure"}, {"to", "to get to", "to finally"}, {"meet", "see", "catch up with"}, {"you", "you again", "you all"}}; for (int j = 0; j < arr.length; j++) { for (int k = 0; k < arr[0].length; k++) { if (k == 1) { System.out.print(arr[j][k] + " "); } } } What, if anything, is printed when the code segment is executed?
Hi, it is great to get to see you again
Consider the following code segment. int[] arr = {1, 2, 4, 0, 3}; for (int i : arr) { System.out.print(i); } Which of the following code segments will produce the same output as the code segment above? I. int[] arr = {1, 2, 4, 0, 3}; for (int i : arr) { System.out.print(arr[i]); } II. int[] arr = {1, 2, 4, 0, 3}; for (int i = 0; i < arr.length; i++) { System.out.print(i); } III. int[] arr = {1, 2, 4, 0, 3}; for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]); }
III only
Consider the following code segment, which is intended to find the average of two positive integers, x and y. int x; int y; int sum = x + y; double average = (double) (sum / 2); Which of the following best describes the error, if any, in the code segment?
In the expression (double) (sum / 2), the cast to double is applied too late, so the average will be less than the expected result for odd values of sum.
Consider the following method, which is intended to calculate and return the expression (�+�)2|�−�|. public double calculate(double x, double y, double a, double b) { return /* missing code */; } Which of the following can replace /* missing code */ so that the method works as intended?
Math.sqrt(Math.pow(x + y, 2) / Math.abs(a - b))
In the Toy class below, the raisePrice method is intended to increase the value of the instance variable price by the value of the parameter surcharge. The method does not work as intended. public class Toy { private String name; private double price; public Toy(String n, double p) { name = n; price = p; } public void raisePrice(double surcharge) // Line 12 { return price + surcharge; // Line 14 } Which of the following changes should be made so that the class definition compiles without error and the method raisePrice works as intended?
Replace line 14 with price += surcharge;.
Consider the following incomplete method, which is intended to return the longest string in the string array words. Assume that the array contains at least one element. public static String longestWord(String[] words) { /* missing declaration and initialization */ for (int k = 1; k < words.length; k++) { if (words[k].length() > longest.length()) { longest = words[k]; } } return longest; } Which of the following can replace /* missing declaration and initialization */ so that the method will work as intended?
String longest = words[0];
Consider the following two class definitions. public class Bike { private int numOfWheels = 2; public int getNumOfWheels() { return numOfWheels; } } public class EBike extends Bike { private int numOfWatts; public EBike(int watts) { numOfWatts = watts; } public int getNumOfWatts() { return numOfWatts; } } The following code segment occurs in a class other than Bike or EBike. Bike b = new EBike(250); System.out.println(b.getNumOfWatts()); System.out.println(b.getNumOfWheels()); Which of the following best explains why the code segment does not compile?
The getNumOfWatts method is not found in the Bike class.
Consider the following Bugs class, which is intended to simulate variations in a population of bugs. The population is stored in the method's int attribute. The getPopulation method is intended to allow methods in other classes to access a Bugs object's population value; however, it does not work as intended. public class Bugs { private int population; public Bugs(int p) { population = p; } public int getPopulation() { return p; } } Which of the following best explains why the getPopulation method does NOT work as intended?
The instance variable population should be returned instead of p, which is local to the constructor.
Consider the following statement. boolean x = (5 < 8) == (5 == 8); What is the value of x after the statement has been executed?
false
Consider the following class definition. public class Password { private String password; public Password (String pwd) { password = pwd; } public void reset(String new_pwd) { password = new_pwd; } } Consider the following code segment, which appears in a method in a class other than Password. The code segment does not compile. Password p = new Password("password"); System.out.println("The new password is " + p.reset("password")); Which of the following best identifies the reason the code segment does not compile?
The reset method does not return a value that can be printed.
public class Thing { public void talk() { System.out.print("Hello "); } public void name() { System.out.print("my friend"); } public void greet() { talk(); name(); } /* Constructors not shown */ } Which of the following code segments, if located in a method in a class other than Thing, will cause the message "Hello my friend" to be printed?
Thing a = new Thing();a.greet();
Consider the following class. public class WindTurbine { private double efficiencyRating; public WindTurbine() { efficiencyRating = 0.0; } public WindTurbine(double e) { efficiencyRating = e; } } Which of the following code segments, when placed in a method in a class other than WindTurbine, will construct a WindTurbine object wt with an efficiencyRating of 0.25 ? Responses
WindTurbine wt = new WindTurbine(0.25);
Which of the following statements stores the value 3 in x ?
int x = 8 % 5;
Consider the following method. public static int getValue(int[] data, int j, int k) { return data[j] + data[k]; } Which of the following code segments, when appearing in another method in the same class as getValue, will print the value 70 ?
int[] arr = {50, 40, 30, 20, 10}; System.out.println(getValue(arr, 1, 2));
Consider the following method. public void changeIt(int[] arr, int index, int newValue) { arr[index] += newValue; } Which of the following code segments, if located in a method in the same class as changeIt, will cause the array myArray to contain {0, 5, 0, 0} ?
int[] myArray = new int[4]; changeIt(myArray, 1, 5);
The following method is intended to print the number of digits in the parameter num. public int numDigits(int num) { int count = 0; while (/* missing condition */) { count++; num = num / 10; } return count; } Which of the following can be used to replace /* missing condition */ so that the method will work as intended?
num != 0
Assume that object references one, two, and three have been declared and instantiated to be of the same type. Assume also that one == two evaluates to true and that two.equals(three) evaluates to false. Consider the following code segment. if (one.equals(two)) { System.out.println("one dot equals two"); } if (one.equals(three)) { System.out.println("one dot equals three"); } if (two == three) { System.out.println("two equals equals three"); } What, if anything, is printed as a result of executing the code segment?
one dot equals two
Consider the following code segment. int a = 10; int b = 5 * 2; System.out.print(a == b); What is printed as a result of executing the code segment? Responses
true
Consider the following class definition. public class RentalCar { private double dailyRate; // the fee per rental day private double mileageRate; // the fee per mile driven public RentalCar(double daily, double mileage) { dailyRate = daily; mileageRate = mileage; } public double calculateFee(int days, int miles) { /* missing code */ } } The calculateFee method is intended to calculate the total fee for renting a car. The total fee is equal to the number of days of the rental, days, times the daily rental rate plus the number of miles driven, miles, times the per mile rate. Which of the following code segments should replace /* missing code */ so that the calculateFee method will work as intended?
return (days * dailyRate) + (miles * mileageRate);
Consider the following code segment. double x = (int) (5.5 - 2.5); double y = (int) 5.5 - 2.5; System.out.println(x - y); What is printed as a result of executing the code segment?
0.5
Consider the following code segment. int num = 1; int count = 0; while (num <= 10) { if (num % 2 == 0 && num % 3 == 0) { count++; } num++; } What value is stored in the variable count as a result of executing the code segment?
1
A two-dimensional array arr is to be created with the following contents. boolean[][] arr = {{false, true, false}, {false, false, true}}; Which of the following code segments can be used to correctly create and initialize arr ?
boolean arr[][] = new boolean[2][3]; arr[0][1] = true; arr[1][2] = true;
Consider the following code segment, where num is an integer variable. int[][] arr = {{11, 13, 14 ,15}, {12, 18, 17, 26}, {13, 21, 26, 29}, {14, 17, 22, 28}}; for (int j = 0; j < arr.length; j++) { for (int k = 0; k < arr[0].length; k++) { if (arr[j][k] == num) { System.out.print(j + k + arr[j][k] + " "); } } } What is printed when num has the value 14 ?
16 17
Consider the following code segment. int[][] array2D = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; for (int[] i : array2D) { for (int x : i) { System.out.print(x + " "); } System.out.println(" "); } How many times will the statement System.out.print(x + " ") be executed? Responses
16 times
Consider the following code segment. double num = 9 / 4; System.out.print(num); System.out.print(" "); System.out.print((int) num); What is printed as a result of executing the code segment?
2.0 2
Consider the following code segment. int x = 7; if (x < 7) { x = 2 * x; } if (x % 3 == 1) { x = x + 2; } System.out.print(3 * x); What is printed as a result of executing the code segment?
27
Consider the following code segment. int[] arr = {3, 1, 0, 4, 2}; for(int j = 0; j < arr.length; j++) { System.out.print(arr[j] + j + " "); } What, if anything, is printed as a result of executing the code segment?
3 2 2 7 6
Consider the following two-dimensional array definition. int[][] data = new int[5][10]; Consider the following code segment, where all elements in data have been initialized. for (int j = 0; j < data.length; j++) { for (int k = 0; k < data[0].length; k++) { if (j == k) { System.out.println(data[j][k]); } } } How many times is the println method called when the code segment is executed? Responses
5
Consider the following code segment. int[][] arr = {{6, 2, 5, 7}, {7, 6, 1, 2}}; for (int j = 0; j < arr.length; j++) { for (int k = 0; k < arr[0].length; k++) { if (arr[j][k] > j + k) { System.out.println("!"); } } } How many times will "!" be printed when the code segment is executed? Responses
6 times
Consider the following code segment. int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {3, 2, 1}}; for (int j = 0; j < arr.length; j++) { for (int k = j; k < arr[0].length; k++) { System.out.print(arr[j][k] + " "); } System.out.println(); } What output is printed when the code segment is executed?
1 2 3 5 6 9
In the code segment below, assume that the int variables a and b have been properly declared and initialized. int c = a; int d = b; c += 3; d--; double num = c; num /= d; Which of the following best describes the behavior of the code segment?
The code segment stores the value of (a + 3) / (b - 1) in the variable num.
Which of the following expressions evaluate to 7 ? I. 9 + 10 % 12 II. (9 + 10) % 12 III. 9 - 2 % 12
II and III
Which of the following statements assigns a random integer between 1 and 10, inclusive, to rn ?
int rn = (int)(Math.random() * 10) + 1;
Consider the following method, count, which is intended to traverse all the elements in the two-dimensional (2D) String array things and return the total number of elements that contain at least one "a". public static int count(String[][] things) { int count = 0; for (int r = 0; r < things.length; r++) { for (int c = 0; c < things[r].length - 1; c++) { if (things[r][c].indexOf("a") >= 0) { count++; } } } return count; } For example, if things contains {{"salad", "soup"}, {"water", "coffee"}}, then count(things) should return 2. The method does not always work as intended. For which of the following two-dimensional array input values does count NOT work as intended?
{{"scarf", "gloves", "hat"}, {"shoes", "shirt", "pants"}}
Consider the following method, which is intended to return true if 0 is found in its two-dimensional array parameter arr and false otherwise. The method does not work as intended. public boolean findZero(int[][] arr) { for (int row = 0; row <= arr.length; row++) { for (int col = 0; col < arr[0].length; col++) { if (arr[row][col] == 0) { return true; } } } return false; } Which of the following values of arr could be used to show that the method does not work as intended?
{{5, 10, 15, 20}, {25, 30, 35, 40}}
The method countTarget below is intended to return the number of times the value target appears in the array arr. The method may not work as intended. public int countTarget(int[] arr, int target) { int count = 0; for (int j = 0; j <= arr.length; j++) // line 4 { if (arr[j] == target) { count++; } } return count; } Which of the following changes, if any, can be made to line 4 so that the method will work as intended?
Changing j <= arr.length; to j < arr.length; (other options include a +/- 1 at the end)
Consider the following class definition. Each object of the class Item will store the item's name as itemName, the item's regular price, in dollars, as regPrice, and the discount that is applied to the regular price when the item is on sale as discountPercent. For example, a discount of 15% is stored in discountPercent as 0.15. public class Item { private String itemName; private double regPrice; private double discountPercent; Which of the following code segments, found in a class other than Item, can be used to create an item with a regular price of $10 and a discount of 25% ? I. Item b = new Item("blanket", 10.0, 0.25); II. Item b = new Item("blanket", 10.0); III. Item b = new Item("blanket", 0.25, 10.0);
I and II only
Consider the following method. public void doSomething() { System.out.println("Something has been done"); } Each of the following statements appears in a method in the same class as doSomething. Which of the following statements are valid uses of the method doSomething ? doSomething(); String output = doSomething(); System.out.println(doSomething());
I only
Consider the following while loop. Assume that the int variable k has been properly declared and initialized. while (k < 0) { System.out.print("*"); k++; } Which of the following ranges of initial values for k will guarantee that at least one "*" character is printed? I. k < 0 II. k = 0 III. k > 0
I only
In the code segment below, assume that the int variable n has been properly declared and initialized. The code segment is intended to print a value that is 1 more than twice the value of n. /* missing code */ System.out.print(result); Which of the following can be used to replace /* missing code */ so that the code segment works as intended? I. int result = 2 * n;result = result + 1; II. int result = n + 1;result = result * 2; III. int result = (n + 1) * 2;
I only
Consider the following class definition. public class Student { private int studentID; private int gradeLevel; private boolean honorRoll; public Student(int s, int g) { studentID = s; gradeLevel = g; honorRoll = false; } public Student(int s) { studentID = s; gradeLevel = 9; honorRoll = false; } } Which of the following code segments would successfully create a new Student object? Student one = new Student(328564, 11); Student two = new Student(238783); int id = 392349;int grade = 11;Student three = new Student(id, grade);
I, II, and III
Consider the following class declaration. public class GameClass { private int numPlayers; private boolean gameOver; public Game() { numPlayers = 1; gameOver = false; } public void addPlayer() { numPlayers++; } public void endGame() { gameOver = true; } } Assume that the GameClass object game has been properly declared and initialized in a method in a class other than GameClass. Which of the following statements are valid? I. game.numPlayers++; II. game.addPlayer(); III. game.gameOver(); IV. game.endGame();
II and IV only
The class contains the withdraw method, which is intended to update the instance variable balance under certain conditions and return a value indicating whether the withdrawal was successful. If subtracting withdrawAmount from balance would lead to a negative balance, balance is unchanged and the withdrawal is considered unsuccessful. Otherwise, balance is decreased by withdrawAmount and the withdrawal is considered successful. Which of the following code segments can replace /* missing code */ to ensure that the withdraw method works as intended? I. if (withdrawAmount > balance) { return "Overdraft"; } else { balance -= withdrawAmount; return true; } II. if (withdrawAmount > balance) { return false; } else { balance -= withdrawAmount; return balance; } III. if (withdrawAmount > balance) { return false; } else { balance -= withdrawAmount; return true; } Responses
III only
Consider the following class definitions. public class C1 { public C1() { /* implementation not shown */ } public void m1() { System.out.print("A"); } public void m2() { System.out.print("B"); } } public class C2 extends C1 { public C2() { /* implementation not shown */ } public void m2() { System.out.print("C"); } } The following code segment appears in a class other than C1 or C2. C1 obj1 = new C2(); obj1.m1(); obj1.m2(); The code segment is intended to produce the output AB. Which of the following best explains why the code segment does not produce the intended output?
Method m2 is executed from the subclass instead of the superclass because obj1 is instantiated as a C2 object.
Consider the following method, which is intended to return the average (arithmetic mean) of the values in an integer array. Assume the array contains at least one element. public static double findAvg(double[] values) { double sum = 0.0; for (double val : values) { sum += val; } return sum / values.length; } Which of the following preconditions, if any, must be true about the array values so that the method works as intended?
No precondition is necessary; the method will always work as intended.
Consider the following code segment, which traverses two integer arrays of equal length. If any element of arr1 is smaller than the corresponding (i.e., at the same index) element of minArray, the code segment should replace the element of minArray with the corresponding element of arr1. After the code segment executes, minArray should hold the smaller of the two elements originally found at the same indices in arr1 and minArray and arr1 should remain unchanged. for (int c = 0; c < arr1.length; c++) { if (arr1[c] < minArray[c]) { arr1[c] = minArray[c]; } else { minArray[c] = arr1[c]; } } Which of the following changes will ensure that the code segment always works as intended?
Removing lines 5-8
Consider the following code segment, which is intended to declare and initialize the two-dimensional (2D) String array things. /* missing code */ = {{"spices", "garlic", "onion", "pepper"}, {"clothing", "hat", "scarf", "gloves"}, {"plants", "tree", "bush", "flower"}, {"vehicles", "car", "boat", "airplane"}}; Which of the following could replace /* missing code */ so that things is properly declared?
String[][] things
Consider the following method. public boolean checkIndexes(double[][] data, int row, int col) { int numRows = data.length; if (row < numRows) { int numCols = data[0].length; return col < numCols; } else { return false; } } Consider the following variable declaration and initialization, which appears in a method in the same class as checkIndexes. double[][] table = new double[5][6]; Which of the following method calls returns a value of true ?
checkIndexes(table, 4, 5)
Consider the following class definition. public class Something { private static int count = 0; public Something() { count += 5; } public static void increment() { count++; } } The following code segment appears in a method in a class other than Something. Something s = new Something(); Something.increment(); Which of the following best describes the behavior of the code segment?
The code segment creates a Something object s. The class Something's static variable count is initially 0, then increased by 5, then increased by 1.
The following code segment is intended to round val to the nearest integer and print the result. double val = -0.7; int roundedVal = (int) (val + 0.5); System.out.println(roundedVal); Which of the following best describes the behavior of the code segment?
The code segment does not work as intended because the expression (int) (val + 0.5) rounds to the nearest integer only when val is positive.
Consider the following code segment, where k and count are properly declared and initialized int variables. k++; k++; count++; k--; count++; k--; Which of the following best describes the behavior of the code segment?
The code segment leaves k unchanged and increases count by 2.
Consider the following code segment, which is intended to print the sum of all elements of an array. int[] arr = {10, 5, 1, 20, 6, 25}; int sum = 0; for (int k = 0; k <= arr.length; k++) { sum += arr[k]; } System.out.println("The sum is " + sum); A runtime error occurs when the code segment is executed. Which of the following changes should be made so that the code segment works as intended?
The for loop header should be replaced with for (int k = 0; k < arr.length; k++).
Consider the following code segment, which is intended to print the digits of the two-digit int number num in reverse order. For example, if num has the value 75, the code segment should print 57. Assume that num has been properly declared and initialized. /* missing code */ System.out.print(onesDigit); System.out.print(tensDigit); Which of the following can be used to replace /* missing code */ so that the code segment works as intended?
int onesDigit = num % 10; int tensDigit = num / 10;
Consider the following class definition. The class does not compile. public class Player { private double score; public getScore() { return score; } // Constructor not shown } The accessor method getScore is intended to return the score of a Player object. Which of the following best explains why the class does not compile?
The return type of the getScore method needs to be defined as double.
Consider the following class definition. public class ItemInventory { private int numItems; public ItemInventory(int num) { numItems = num; } public updateItems(int newNum) { numItems = newNum; } } Which of the following best identifies the reason the class does not compile? Responses
The updateItems method is missing a return type.
Consider the following class definition. public class FishTank { private double numGallons; private boolean saltWater; public FishTank(double gals, boolean sw) { numGallons = gals; saltWater = sw; } public double getNumGallons() { return numGallons; } public boolean isSaltWater() { if (saltWater) { return "Salt Water"; } else { return "Fresh Water"; } } } Which of the following best explains the reason why the class will not compile?
The value returned by the isSaltWater method is not compatible with the return type of the method.
Consider the following class, which uses the instance variable balance to represent a bank account balance. public class BankAccount { private double balance; public double deposit(double amount) { /* missing code */ } } The deposit method is intended to increase the account balance by the deposit amount and then return the updated balance. Which of the following code segments should replace /* missing code */ so that the deposit method will work as intended?
balance = balance + amount; return balance;
Consider the following statement, which assigns a value to b1. boolean b1 = true && (17 % 3 == 1); Which of the following assigns the same value to b2 as the value stored in b1 ?
boolean b2 = false && (17 % 3 == 2);
Consider the code segment below, where arr is a one-dimensional array of integers. int sum = 0; for (int n : arr) { sum = sum + 2 * n; } System.out.print(sum); Which of the following code segments will produce the same output as the code segment above?
int sum = 0; for (int k = 0; k < arr.length; k++) { sum = sum + 2 * arr[k]; } System.out.print(sum);
A school that does not have air conditioning has published a policy to close school when the outside temperature reaches or exceeds 95°F. The following code segment is intended to print a message indicating whether or not the school is open, based on the temperature. Assume that the variable degrees has been properly declared and initialized with the outside temperature. if (degrees > 95) { System.out.println("School will be closed due to extreme heat"); } else { System.out.println("School is open"); } Which of the following initializations for degrees, if any, will demonstrate that the code segment may not work as intended?
degrees = 95;
A student has created a Song class. The class contains the following variables. A String variable called artist to represent the artist name A String variable called title to represent the song title A String variable called album to represent the album title The object happyBirthday will be declared as type Song. Which of the following statements is true?
happyBirthday is an instance of the Song class.
On Sunday night, a meteorologist records predicted daily high temperatures, in degrees Fahrenheit, for the next seven days. At the end of each day, the meteorologist records the actual daily high temperature, in degrees Fahrenheit. At the end of the seven-day period, the meteorologist would like to find the greatest absolute difference between a predicted temperature and a corresponding actual temperature. Consider the following method, which is intended to return the greatest absolute difference between any pair of corresponding elements in the int arrays pred and act. /** Precondition: pred and act have the same non-zero length. */ public static int diff(int[] pred, int[] act) { int num = Integer.MIN_VALUE; for (int i = 0; i < pred.length; i++) { /* missing code */ } return num; } Which of the following code segments can be used to replace /* missing code */ so that diff will work as intended?
if (Math.abs(pred[i] - act[i]) > num) { num = Math.abs(pred[i] - act[i]); }
Consider the following code segment. if (a < b || c != d) { System.out.println("dog"); } else { System.out.println("cat"); } Assume that the int variables a, b, c, and d have been properly declared and initialized. Which of the following code segments produces the same output as the given code segment for all values of a, b, c, and d ?
if (a >= b && c == d) { System.out.println("cat"); } else { System.out.println("dog"); }
Consider the following code segment. String alpha = new String("APCS"); String beta = new String("APCS"); String delta = alpha; System.out.println(alpha.equals(beta)); System.out.println(alpha == beta); System.out.println(alpha == delta); What is printed as a result of executing the code segment?
true false true
Consider the following code segment. int k = 0; /* missing loop header */ { k++; System.out.print(k + " "); } Which of the following can be used as a replacement for /* missing loop header */ so that the code segment prints out the string "1 2 3 4 "? Responses
while (k < 4)
Consider the following code segment, which is intended to print the sum of all the odd integers from 0 up to and including 101. int r = 0; int sum = 0; /* missing loop header */ { if (r % 2 == 1) { sum += r; } r++; } System.out.println(sum); Which of the following could replace /* missing loop header */ to ensure that the code segment will work as intended?
while (r <= 101)
Consider the following Boolean expression in which the int variables x and y have been properly declared and initialized. (x <= 10) == (y > 25) Which of the following values for x and y will result in the expression evaluating to true ?
x = 10 and y = 30
Consider the following code segment. int x = 3; int y = -1; if (x - 2 > y) { x -= y; } if (y + 3 >= x) { y += x; } System.out.print("x = " + x + " y = " + y); What is printed as a result of the execution of the code segment?
x = 4 y = -1
The following code segment is intended to interchange the values of the int variables x and y. Assume that x and y have been properly declared and initialized. int temp = x; /* missing code */ Which of the following can be used to replace /* missing code */ so that the code segment works as intended?
x = y; y = temp;
Consider the following code segment. int[] arr = {1, 2, 3, 4, 5, 6, 7}; for (int i = 1; i < arr.length; i += 2) { arr[i] = arr[i - 1]; } Which of the following represents the contents of the array arr after the code segment is executed?
{1, 1, 3, 3, 5, 5, 7}
Consider the following code segment. boolean[] oldVals = {true, false, true, true}; boolean[] newVals = new boolean[4]; for (int j = oldVals.length - 1; j >= 0; j--) { newVals[j] = !(oldVals[j]); } What, if anything, will be the contents of newVals as a result of executing the code segment?
{false, true, false, false}