copy

Ace your homework & exams now with Quizwiz!

Assume that x and y have been declared and initialized with int values. Consider the following Java expression. (y>1000) || (x>1000 && x<1500) Which of the following is equivalent to the expression given above? A (y > 10000 | | x > 1000) && (y > 10000 | | x < 1500) B (y > 10000 | | x > 1000) | | (y > 10000 | | x < 1500) C (y > 10000) && (x > 1000 | | x < 1500) D (y > 10000 && x > 1000) | | (y > 10000 && x < 1500) E (y > 10000 && x > 1000) && (y > 10000 && x < 1500)

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

Consider the following code segment. double d1 = 10.0; Double d2 = 20.0; Double d3 = new Double(30.0); double d4 = new Double(40.0); System.out.println(d1 + d2 + d3.doubleValue() + d4); What, if anything, is printed when the code segment is executed? A 100.0 B 10.050.040.0 C 10.020.070.0 D 10.020.030.040.0 E There is no output due to a compilation error.

A 100.0

Consider the following method. public int getTheResult(int n) { int product = 1; for (int number = 1; number < n; number++) { if (number % 2 == 0) product *= number; } return product; } What value is returned as a result of the call getTheResult(8) ? A 48 B 105 C 384 D 5040 E 40320

A 48

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 ? I. doSomething(); II. String output = doSomething(); III. System.out.println(doSomething()); A I only B II only C I and II only D I and III only E I, II, and III

A I only

Consider the following code segments, which are each intended to convert grades from a 100-point scale to a 4.0-point scale and print the result. A grade of 90 or above should yield a 4.0, a grade of 80 to 89 should yield a 3.0, a grade of 70 to 79 should yield a 2.0, and any grade lower than 70 should yield a 0.0. Assume that grade is an int variable that has been properly declared and initialized. Code Segment I double points = 0.0; if (grade > 89) { points += 4.0; } else if (grade > 79) { points += 3.0; } else if (grade > 69) { points += 2.0; } else { points += 0.0; } System.out.println(points); Code Segment II double points = 0.0; if (grade > 89) { points += 4.0; } if (grade > 79) { grade += 3.0; } if (grade > 69) { points += 2.0; } if (grade < 70) { points += 0.0; } System.out.println(points); Which of the following statements correctly compares the values printed by the two methods? A The two code segments print the same value only when grade is below 80. B The two code segments print the same value only when grade is 90 or above or grade is below 80. C The two code segments print the same value only when grade is 90 or above. D Both code segments print the same value for all possible values of grade. E The two code segments print different values for all possible values of grade.

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

Assume that x and y are boolean variables and have been properly initialized. (x && y) || !(x && y) The result of evaluating the expression above is best described as A always true B always false C true only when x is true and y is true D true only when x and y have the same value E true only when x and y have different values

A always true

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= -1); } Which of the following method calls demonstrates that the method does not work as intended? 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")

Assume that object references one, two, and three have been declared and instantiated to be of the same type. Assume also that one == two evaluates to true and that two.equals(three) evaluates to false. Consider the following code segment. if (one.equals(two)) { System.out.println("one dot equals two"); } if (one.equals(three)) { System.out.println("one dot equals three"); } if (two == three) { System.out.println("two equals equals three"); } What, if anything, is printed as a result of executing the code segment? A one dot equals two B one dot equals two one dot equals three C one dot equals three two equals equals three D one dot equals two one dot equals three two equals equals three E Nothing is printed.

A one dot equals two

Consider the following code segment, which is intended to simulate a random process. The code is intended to set the value of the variable event to exactly one of the values 1, 2, or 3, depending on the probability of an event occurring. The value of event should be set to 1 if the probability is 70 percent or less. The value of event should be set to 2 if the probability is greater than 70 percent but no more than 80 percent. The value of event should be set to 3 if the probability is greater than 80 percent. The variable randomNumber is used to simulate the probability of the event occurring. int event = 0; if (randomNumber <= 0.70) { event = 1; } if (randomNumber <= 0.80) { event = 2; } else { event = 3; } The code does not work as intended. Assume that the variable randomNumber has been properly declared and initialized. Which of the following initializations for randomNumber will demonstrate that the code segment will not work as intended? A randomNumber = 0.70; B randomNumber = 0.80; C randomNumber = 0.85; D randomNumber = 0.90; E randomNumber = 1.00;

A randomNumber = 0.70;

Assume that the boolean variables a, b, c, and d have been declared and initialized. Consider the following expression. !( !( a && b ) || ( c || !d )) Which of the following is equivalent to the expression? A. ( a && b ) && ( !c && d ) B. ( a || b ) && ( !c && d ) C. ( a && b ) || ( c || !d ) D. ( !a || !b ) && ( !c && d ) E. !( a && b ) && ( c || !d )

A. ( a && b ) && ( !c && d )

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? A. 1 B. 3 C. 5 D. 7 E. 8

A. 1

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? A. 8 B. 8.0 C. 9 D. 9.0 E. 10

A. 8

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? A. 8/4 B. 5/1 C. 4/8 D. 2/1 E. 1/5

A. 8/4

Consider the following code segment. int value = 15; while (value < 28) { System.out.println(value); value++; } What are the first and last numbers output by the code segment? A. First: 15 Last: 27 B. First: 15 Last: 28 C. First: 16 Last: 27 D. First: 16 Last: 28 E. First: 16 Last: 29

A. First: 15 Last: 27

A teacher put three bonus questions on a test and awarded 5 extra points to anyone who answered all three bonus questions correctly and no extra points otherwise. Assume that the boolean variables bonusOne, bonusTwo, and bonusThree indicate whether a student has answered the particular question correctly.Each variable was assigned true if the answer was correct and false if the answer was incorrect. Which of the following code segments will properly update the variable grade based on a student's performance on the bonus questions? I. if (bonusOne && bonusTwo && bonusThree) grade += 5; II. if (bonusOne || bonusTwo || bonusThree) grade += 5; III. if (bonusOne) grade += 5; if (bonusTwo) grade += 5; if (bonusThree) grade += 5; A. I only B. II only C. III only D. I and III E. II and III

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

A. I only

Which of the following expressions evaluate to 3.5 ? I. (double) 2 / 4 + 3 II. (double) (2 / 4) + 3 III. (double) (2 / 4 + 3) A. I only B. III only C. I and II only D. II and III only E. I, II, and III

A. I only

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? A. The code segment compiles without error. B. The code segment does not compile, because the int variable x cannot be assigned the result of the operation w / 2. C. The code segment does not compile, because the integer value 3 cannot be assigned to the double variable y. D. The code segment does not compile, because the operands of the addition operator cannot be of different types int and double. E. The code segment does not compile because the result of the addition operation is of type double and cannot be cast to an int.

A. The code segment compiles without error.

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? A. x B. y C. x && y D. x | | y E. x != y

A. x

Consider the following code segment. int one = 1; int two = 2; String zee = "Z"; System.out.println(one + two + zee); What is printed as a result of executing the code segment? A 12Z B 3Z C 12zee D 3zee E onetwozee

B 3Z

Consider the following code segment. int x = /* some integer value */ ; int y = /* some integer value */ ; boolean result = (x < y); result = ( (x >= y) && !result ); Which of the following best describes the conditions under which the value of result will be true after the code segment is executed? A Only when x < y B Only when x >= y C Only when x and y are equal D The value will always be true. E The value will never be true.

B Only when x >= y

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? A Person p = new Person ("Homer", "adult"); B Person p = new Person ("Homer", 23); C Person p = new Person ("Homer", "23"); D Person p = new Person ("Homer", true); E Person p = new Person ("Homer", 17);

B Person p = new Person ("Homer", 23);

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

B The updateItems method is missing a return type.

Which of the following best describes the value of the Boolean expression shown below? a && !(b || a) A The value is always true. B The value is always false. C The value is true when a has the value false, and is false otherwise. D The value is true when b has the value false, and is false otherwise. E The value is true when either a or b has the value true, and is false otherwise.

B The value is always false.

Consider the following code segment. int j = 1; while (j < 5) { int k = 1; while (k < 5) { System.out.println(k); k++; } j++; } Which of the following best explains the effect, if any, of changing the first line of code to int j = 0; ? A There will be one more value printed because the outer loop will iterate one additional time. B There will be four more values printed because the outer loop will iterate one additional time. C There will be one less value printed because the outer loop will iterate one fewer time. D There will be four fewer values printed because the outer loop will iterate one fewer time. E There will be no change to the output of the code segment.

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

The question refer to the code from the GridWorld case study. Consider the following code segment. Location loc1 = new Location(3, 3); Location loc2 = new Location(3, 2); if (loc1.equals(loc2.getAdjacentLocation(Location.EAST))) System.out.print("aaa"); if (loc1.getRow() == loc2.getRow()) System.out.print("XXX"); if (loc1.getDirectionToward(loc2) == Location.EAST) System.out.print("555"); What will be printed as a result of executing the code segment? A aaaXXX555 B aaaXXX C XXX555 D 555 E aaa

B aaaXXX

Consider the following statement, which assigns a value to b1. boolean b1 = true && (17 % 3 == 1); Which of the following assigns the same value to b2 as the value stored in b1 ? A boolean b2 = false || (17 % 3 == 2); B boolean b2 = false && (17 % 3 == 2); C boolean b2 = true || (17 % 3 == 1); D boolean b2 = (true || false) && true; E boolean b2 = (true && false) || true;

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

Assume that x and y are boolean variables and have been properly initialized. (x && y) && !(x || y) Which of the following best describes the result of evaluating the expression above? A true always B false always C true only when x is true and y is true D true only when x and y have the same value E true only when x and y have different values

B false always

Consider the following methods, which appear in the same class. public int function1(int i, int j) { return i + j; } public int function2(int i, int j) { return j - i; } Which of the following statements, if located in a method in the same class, will initialize the variable x to 11? A int x = function2(4, 5) + function1(1, 3); B int x = function1(4, 5) + function2(1, 3); C int x = function1(4, 5) + function2(3, 1); D int x = function1(3, 1) + function2(4, 5); E int x = function2(3, 1) + function1(4, 5);

B int x = function1(4, 5) + function2(1, 3);

Consider the following declarations. int valueOne, valueTwo; Assume that valueOne and valueTwo have been initialized. Which of the following evaluates to true if valueOne and valueTwo contain the same value? A valueOne.equals((Object) valueTwo) B valueOne == valueTwo C valueOne.compareTo((Object) valueTwo) == 0 D valueOne.compareTo(valueTwo) == 0 E valueOne.equals(valueTwo)

B valueOne == valueTwo

Assume that a and b have been defined and initialized as int values. The expression ! ( ! (a != b ) && (b > 7) ) is equivalent to which of the following? A. (a!=b) || (b<7) B. (a!=b) || (b<=7) C. (a==b) || (b<=7) D. (a!=b) && (b<=7) E. (a==b) && (b>7)

B. (a!=b) || (b<=7)

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? A. 2 2 B. 2.0 2 C. 2.0 2.0 D. 2.25 2 E. 2.25 2.0

B. 2.0 2

Consider the following code segment. String str1 = new String("Advanced Placement"); String str2 = new String("Advanced Placement"); if (str1.equals(str2) && str1 == str2) { System.out.println("A");} else if (str1.equals(str2) && str1 != str2) { System.out.println("B"); } else if (!str1.equals(str2) && str1 == str2) { System.out.println("C"); } else if (!str1.equals(str2) && str1 != str2) { System.out.println("D"); } What, if anything, is printed when the code segment is executed? A. A B. B C. C D. D E. Nothing is printed.

B. B

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

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

Consider the following class definitions. public class Person { private String name; public String getName() { return name; } } public class Book { private String author; private String title; private Person borrower; public Book(String a, String t) { author = a; title = t; borrower = null; } public void printDetails() { System.out.print("Author: " + author + " Title: " + title); if ( /* missing condition */ ) { System.out.println(" Borrower: " + borrower.getName()); } } public void setBorrower(Person b) { borrower = b; } } Which of the following can replace /* missing condition */ so that the printDetails method CANNOT cause a run-time error? I. !borrower.equals(null) II. borrower != null III. borrower.getName() != null A. I only B. II only C. III only D. I and II E. II and III

B. II only

Assume that the boolean variables a and b have been declared and initialized. Consider the following expression. (a && (b || !a)) == a && b Which of the following best describes the conditions under which the expression will evaluate to true? A. Only when a is true B. Only when b is true C. Only when both a and b are true D. The expression will never evaluate to true. E. The expression will always evaluate to true.

B. Only when b is true

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? A. The code segment stores the value of (a + 3) / b in the variable num. B. The code segment stores the value of (a + 3) / (b - 1) in the variable num. C. The code segment stores the value of (a + 3) / (b - 2) in the variable num. D. The code segment stores the value of (a + 3) / (1 - b) in the variable num. E. The code segment causes a runtime error in the last line of code because num is type double and d is type int.

B. The code segment stores the value of (a + 3) / (b - 1) in the variable num.

Consider the following code segment. for (int x = 0; x <= 4; x++) // Line 1 { for (int y = 0; y < 4; y++) // Line 3 { System.out.print("a"); } System.out.println(); } Which of the following best explains the effect of simultaneously changing x <= 4 to x < 4 in line 1 and y < 4 to y <= 4 in line 3 ? A "a" will be printed fewer times because while each output line will have the same length as before, the number of lines printed will decrease by 1. B "a" will be printed more times because while the number of output lines will be the same as before, the length of each output line will increase by 1. C "a" will be printed the same number of times because while the number of output lines will decrease by 1, the length of each line will increase by 1. D "a" will be printed more times because both the number of output lines and the length of each line will increase by 1. E The output of the code segment will not change in any way.

C "a" will be printed the same number of times because while the number of output lines will decrease by 1, the length of each line will increase by 1.

Consider the following code segment. int a = 5; int b = 2; double c = 3.0; System.out.println(5 + a / b * c - 1); What is printed when the code segment is executed? A 0.666666666666667 B 9.0 C 10.0 D 11.5 E 14.0

C 10.0

Consider the following code segments. Code segment 2 is a revision of code segment 1 in which the loop increment has been changed. Code Segment 1 int sum = 0; for (int k = 1; k <= 30; k++) { sum += k; } System.out.println("The sum is: " + sum); Code Segment 2 int sum = 0; for (int k = 1; k <= 30; k = k + 2) { sum += k; } System.out.println("The sum is: " + sum); Code segment 1 prints the sum of the integers from 1 through 30, inclusive. Which of the following best explains how the output changes from code segment 1 to code segment 2 ? A Code segment 1 and code segment 2 will produce the same output. B Code segment 2 will print the sum of only the even integers from 1 through 30, inclusive because it starts sum at zero, increments k by twos, and terminates when k exceeds 30. C Code segment 2 will print the sum of only the odd integers from 1 through 30, inclusive because it starts k at one, increments k by twos, and terminates when k exceeds 30. D Code segment 2 will print the sum of only the even integers from 1 through 60, inclusive because it starts sum at zero, increments k by twos, and iterates 30 times. E Code segment 2 will print the sum of only the odd integers from 1 through 60, inclusive because it starts k at one, increments k by twos, and iterates 30 times.

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

Consider the following code segment. int x = 5; int y = 6; /* missing code */ z = (x + y) / 2; Which of the following can be used to replace /* missing code */ so that the code segment will compile? I. int z = 0; II. int z; III. boolean z = false; A I only B II only C I and II only D II and III only E I, II, and III

C I and II only

Consider the following method definition. The method printAllCharacters is intended to print out every character in str, starting with the character at index 0. public static void printAllCharacters(String str) { for (int x = 0; x < str.length(); x++) // Line 3 { System.out.print(str.substring(x, x + 1)); } } The following statement is found in the same class as the printAllCharacters method. printAllCharacters("ABCDEFG"); Which choice best describes the difference, if any, in the behavior of this statement that will result from changing x < str.length() to x <= str.length() in line 3 of the method? A The method call will print fewer characters than it did before the change because the loop will iterate fewer times. B The method call will print more characters than it did before the change because the loop will iterate more times. C The method call, which worked correctly before the change, will now cause a run-time error because it attempts to access a character at index 7 in a string whose last element is at index 6. D The method call, which worked correctly before the change, will now cause a run-time error because it attempts to access a character at index 8 in a string whose last element is at index 7. E The behavior of the code segment will remain unchanged.

C The method call, which worked correctly before the change, will now cause a run-time error because it attempts to access a character at index 7 in a string whose last element is at index 6.

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? A The getScore method should be declared as private. B The getScore method requires a parameter. C The return type of the getScore method needs to be defined as double. D The return type of the getScore method needs to be defined as String. E The return type of the getScore method needs to be defined as void.

C The return type of the getScore method needs to be defined as double.

The following questions refer to the code from the GridWorld case study. A copy of the code is provided below. Appendix B — Testable API info.gridworld.grid.Location class (implements Comparable) public Location(int r, int c) constructs a location with given row and column coordinates public int getRow() returns the row of this location public int getCol() returns the column of this location public Location getAdjacentLocation(int direction) returns the adjacent location in the direction that is closest to direction public int getDirectionToward(Location target) returns the closest compass direction from this location toward target public boolean equals(Object other) returns true if other is a Location with the same row and column as this location; false otherwise public int hashCode() returns a hash code for this location public int compareTo(Object other) returns a negative integer if this location is less than other, zero if the two locations are equal, or a positive integer if this location is greater than other. Locations are ordered in row-major order. Precondition: other is a Location object. public String toString() returns a string with the row and column of this location, in the format (row, col) Compass directions: public static final int NORTH = 0; public static final int EAST = 90; public static final int SOUTH = 180; public static final int WEST = 270; public static final int NORTHEAST = 45; public static final int SOUTHEAST = 135; public static final int SOUTHWEST = 225; public static final int NORTHWEST = 315; Turn angles: public static final int LEFT = -90; public static final int RIGHT = 90; public static final int HALF_LEFT = -45; public static final int HALF_RIGHT = 45; public static final int FULL_CIRCLE = 360; public static final int HALF_CIRCLE = 180; public static final int AHEAD = 0; info.gridworld.grid.Grid<E> interface int getNumRows() returns the number of rows, or -1 if this grid is unbounded int getNumCols() returns the number of columns, or -1 if this grid is unbounded boolean isValid(Location loc) returns true if loc is valid in this grid, false otherwise Precondition: loc is not null E put(Location loc, E obj) puts obj at location loc in this grid and returns the object previously at that location (or null if the location was previously unoccupied). Precondition: (1) loc is valid in this grid (2) obj is not null E remove(Location loc) removes the object at location loc from this grid and returns the object that was removed (or null if the location is unoccupied) Precondition: loc is valid in this grid E get(Location loc) returns the object at location loc (or null if the location is unoccupied) Precondition: loc is valid in this grid ArrayList<Location> getOccupiedLocations() returns an array list of all occupied locations in this grid ArrayList<Location> getValidAdjacentLocations(Location loc) returns an array list of the valid locations adjacent to loc in this grid Precondition: loc is valid in this grid ArrayList<Location> getEmptyAdjacentLocations(Location loc) returns an array list of the valid empty locations adjacent to loc in this grid Precondition: loc is valid in this grid ArrayList<Location> getOccupiedAdjacentLocations(Location loc) returns an array list of the valid occupied locations adjacent to loc in this grid Precondition: loc is valid in this grid ArrayList<E> getNeighbors(Location loc) returns an array list of the objects in the occupied locations adjacent to loc in this grid Precondition: loc is valid in this grid info.gridworld.actor.Actor class public Actor() constructs a blue actor that is facing north public Color getColor() returns the color of this actor public void setColor(Color newColor) sets the color of this actor to newColor public int getDirection() returns the direction of this actor, an angle between 0 and 359 degrees public void setDirection(int newDirection) sets the direction of this actor to the angle between 0 and 359 degrees that is equivalent to newDirection public Grid<Actor> getGrid() returns the grid of this actor, or null if this actor is not contained in a grid public Location getLocation() returns the location of this actor, or null if this actor is not contained in a grid public void putSelfInGrid(Grid<Actor> gr, Location loc) puts this actor into location loc of grid gr. If there is another actor at loc, it is removed. Precondition: (1) This actor is not contained in a grid (2) loc is valid in gr public void removeSelfFromGrid() removes this actor from its grid. Precondition: this actor is contained in a grid public void moveTo(Location newLocation) moves this actor to newLocation. If there is another actor at newLocation, it is removed. Precondition: (1) This actor is contained in a grid (2) newLocation is valid in the grid of this actor public void act() reverses the direction of this actor. Override this method in subclasses of Actor to define types of actors with different behavior public String toString() returns a string with the location, direction, and color of this actor info.gridworld.actor.Rock class (extends Actor) public Rock() constructs a black rock public Rock(Color rockColor) constructs a rock with color rockColor public void act() overrides the act method in the Actor class to do nothing info.gridworld.actor.Flower class (extends Actor) public Flower() constructs a pink flower public Flower(Color initialColor) constructs a flower with color initialColor public void act() causes the color of this flower to darken Consider the following method that is intended to move the parameter anActor to a different grid that is referred to by the parameter newGrid. The location of anActor in newGrid should be the same as the location that anActor had occupied in its original grid. /** Moves anActor to newGrid in the same location it occupied in its original grid. * @param anActor the actor to be moved * @param newGrid the grid in which the actor is to be placed */ public void moveActorToNewGrid(Actor anActor, Grid<Actor> newGrid) { Grid<Actor> oldGrid = anActor.getGrid(); Location loc = anActor.getLocation(); /* missing code */ } Which of the following can be used to replace /* missing code */ so that moveActorToNewGrid will work as intended? A anActor.putSelfInGrid(newGrid, loc); anActor.removeSelfFromGrid(); B oldGrid.remove(loc); anActor.putSelfInGrid(newGrid, loc); C anActor.removeSelfFromGrid(); anActor.putSelfInGrid(newGrid, loc); D oldGrid.remove(loc); newGrid.put(anActor, loc); E newGrid.put(anActor, loc); oldGrid.remove(loc);

C anActor.removeSelfFromGrid(); anActor.putSelfInGrid(newGrid, loc);

Consider the following two code segments where the int variable choice has been properly declared and initialized. Code Segment A if (choice > 10) { System.out.println("blue"); } else if (choice < 5) { System.out.println("red"); } else { System.out.println("yellow"); } Code Segment B if (choice > 10) { System.out.println("blue"); } if (choice < 5) { System.out.println("red"); } else { System.out.println("yellow"); } Assume that both code segments initialize choice to the same integer value. Which of the following best describes the conditions on the initial value of the variable choice that will cause the two code segments to produce different output? A choice < 5 B choice >= 5 and choice <= 10 C choice > 10 D choice == 5 or choice == 10 E There is no value for choice that will cause the two code segments to produce different output.

C choice > 10

A code segment (not shown) is intended to determine the number of players whose average score in a game exceeds 0.5. A player's average score is stored in avgScore, and the number of players who meet the criterion is stored in the variable count. Which of the following pairs of declarations is most appropriate for the code segment described? A double avgScore; boolean count; B double avgScore; double count; C double avgScore; int count; D int avgScore; boolean count; E int avgScore; int count;

C double avgScore; int count;

The code segment below is intended to calculate the circumference c of a circle with the diameter d of 1.5. The circumference of a circle is equal to its diameter times pi. /* missing declarations */ c = pi * d; Which of the following variable declarations are most appropriate to replace /* missing declarations */ in this code segment? A int pi = 3.14159; int d = 1.5; final int c; B final int pi = 3.14159; int d = 1.5; int c; C final double pi = 3.14159; double d = 1.5; double c; D double pi = 3.14159; double d = 1.5; final double c = 0.0; E final double pi = 3.14159; final double d = 1.5; final double c = 0.0;

C final double pi = 3.14159; double d = 1.5; double c;

Which of the following code segments produces the output "987654321" ? A int num = 10; while (num > 0) { System.out.print(num); num--; } B int num = 10; while (num >= 0) { System.out.print(num); num--; } C int num = 10; while (num > 1) { num--; System.out.print(num); } D int num = 10; while (num >= 1) { num--; System.out.print(num); } E int num = 0; while (num <= 9) { System.out.print(10 - num); num++;

C int num = 10; while (num > 1) { num--; System.out.print(num); }

Consider the following method. public int compute(int n, int k) { int answer = 1; for (int i = 1; i <= k; i++) answer *=n; return answer; } Which of the following represents the value returned as a result of the call compute (n, k) ? A n*k B n! C n^k D 2^k E k^n

C n^k

Consider the following class definition. public class Example { private int x; // Constructor not shown. } Which of the following is a correct header for a method of the Example class that would return the value of the private instance variable x so that it can be used in a class other than Example ? A private int getX() B private void getX() C public int getX() D public void getX() E public void getX(int x)

C public int getX()

Consider the following two code segments. Assume that the int variables m and n have been properly declared and initialized and are both greater than 0. I. for (int i = 0; i < m * n; i++){ System.out.print("A");} II. for (int j = 1; j <= m; j++){ for (int k = 1; k < n; k++) { System.out.print("B"); }} Assume that the initial values of m and n are the same in code segment I as they are in code segment II. Which of the following correctly compares the number of times that "A" and "B" are printed when each code segment is executed? A. "A" is printed m fewer times than "B". B. "A" is printed n fewer times than "B". C. "A" is printed m more times than "B". D. "A" is printed n more times than "B". E. "A" and "B" are printed the same number of times.

C. "A" is printed m more times than "B".

Consider the following class declaration public class SomeClass { private int num; public SomeClass(int n) { num = n; } public void increment(int more) { num = num + more; } public int getNum() { return num; } } The following code segment appears in another class. SomeClass one = new SomeClass(100); SomeClass two = new SomeClass(100); SomeClass three = one; one.increment(200); System.out.println(one.getNum() + " " + two.getNum() + " " + three.getNum()); What is printed as a result of executing the code segment? A. 100 100 100 B. 300 100 100 C. 300 100 300 D. 300 300 100 E. 300 300 300

C. 300 100 300

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? A. 2 B. 4 C. 9 D. 9.5 E. 19

C. 9

Consider the following code segment. String oldStr = "ABCDEF"; String newStr = oldStr.substring(1, 3) + oldStr.substring(4); System.out.println(newStr); What is printed as a result of executing the code segment? A. ABCD B. BCDE C. BCEF D. BCDEF E. ABCDEF

C. BCEF

Consider the following method. public void conditionalTest(int a, int b) { if ((a > 0) && (b > 0)) { if (a > b) System.out.println("A"); else System.out.println("B"); } else if ((b < 0) || (a < 0)) System.out.println("C"); else System.out.println("D"); } What is printed as a result of the call conditionalTest(3, -2)? A. A B. B C. C D. D E. Nothing is printed.

C. C

Consider the following 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? A. biggest always returns the value of a. B. biggest may not work correctly when c has the greatest value. C. biggest may not work correctly when a and b have equal values. D. biggest may not work correctly when a and c have equal values. E. biggest may not work correctly when b and c have equal values.

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

Consider the following method. public double myMethod(int a, boolean b) { /* implementation not shown */ } Which of the following lines of code, if located in a method in the same class as myMethod, will compile without error? A. int result = myMethod(2, false); B. int result = myMethod(2.5, true); C. double result = myMethod(0, false); D. double result = myMethod(true, 10); E. double result = myMethod(2.5, true);

C. double result = myMethod(0, false);

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

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

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? A. private int day; private int month; private int year; private Date() { /* implementation not shown */ } private void setDate(int d, int m, int y) { /* implementation not shown */ } B. private int day; private int month; private int year; public Date() { /* implementation not shown */ } private void setDate(int d, int m, int y) { /* implementation not shown */ } C. 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 */ } D. public int day; public int month; public int year; private Date() { /* implementation not shown */ } private void setDate(int d, int m, int y) { /* implementation not shown */ } E. public int day; public int month; public int year; public Date() { /* implementation not shown */ } public void setDate(int d, int m, int y) { /* implementation not shown */ }

C. 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 */ }

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? A. private int score; private int id; private Player(int playerScore, int playerID) { /* implementation not shown */ } private int getScore() { /* implementation not shown */ } B. private int score; private int id; public Player(int playerScore, int playerID) { /* implementation not shown */ } private int getScore() { /* implementation not shown */ } C. private int score; private int id; public Player(int playerScore, int playerID) { /* implementation not shown */ } public int getScore() { /* implementation not shown */ } D. public int score; public int id; public Player(int playerScore, int playerID) { /* implementation not shown */ } private int getScore() { /* implementation not shown */ } E. public int score; public int id; public Player(int playerScore, int playerID) { /* implementation not shown */ } public int getScore() { /* implementation not shown */ }

C. private int score; private int id; public Player(int playerScore, int playerID) { /* implementation not shown */ } public int getScore() { /* implementation not shown */ }

Consider the following static method. public static int calculate(int x) { x = x + x; x = x + x; x = x + x; return x; } Which of the following can be used to replace the body of calculate so that the modified version of calculate will return the same result as the original version for all x ? A. return 2 * x; B. return 4 * x; C. return 8 * x; D. return 3 * calculate(x); E. return x + calculate(x - 1);

C. return 8 * x;

Consider the following code segment. int count = 5; while (count < 100) { count = count * 2; } count = count + 1; What will be the value of count as a result of executing the code segment? A 100 B 101 C 160 D 161 E 321

D 161

Consider the following 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? A 4.0 B 5.0 C 80.0 D 84.0 E 85.0

D 84.0

Consider the following Boolean expressions. I. A && B II. !A && !B Which of the following best describes the relationship between values produced by expression I and expression II? A Expression I and expression II evaluate to different values for all values of A and B. B Expression I and expression II evaluate to the same value for all values of A and B. C Expression I and expression II evaluate to the same value only when A and B are the same. D Expression I and expression II evaluate to the same value only when A and B differ. E Expression I and expression II evaluate to the same value whenever A is true.

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

Consider the following 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; public Item (String name, double price, double discount) { itemName = name; regPrice = price; discountPercent = discount; } public Item (String name, double price) { itemName = name; regPrice = price; discountPercent = 0.25; } /* Other methods not shown */ } 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 III. Item("blanket", 10.0); Item b = new Item("blanket", 0.25, 10.0); A I only B II only C III only D I and II only E I, II, and III

D I and II only

Consider the following code segment in which the int variable x has been properly declared and initialized. if (x % 2 == 1) { System.out.println("YES"); } else { System.out.println("NO"); } Assuming that x is initialized to the same positive integer value as the original, which of the following code segments will produce the same output as the original code segment? I. if (x % 2 == 1) { System.out.print("YES"); } if (x % 2 == 0) { System.out.println("NO"); } II. if (x % 2 == 1) { System.out.println("YES"); } else if (x % 2 == 0) { System.out.println("NO"); } else { System.out.println("NONE"); } III. boolean test = x % 2 == 0; if (test) { System.out.println("YES"); } else { System.out.println("NO"); } A I only B II only C III only D I and II only E I, II, and III

D I and II only

Consider the following 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(); A IV only B I and III only C I and IV only D II and IV only E II, III, and IV only

D II and IV only

Consider the following code segment. The code is intended to read nonnegative numbers and compute their product until a negative number is read; however, it does not work as intended. (Assume that the readInt method correctly reads the next number from the input stream.) int k = 0; int prod = 1; while (k >= 0) { System.out.print("enter a number: "); k = readInt(); // readInt reads the next number from input prod = prod * k; } System.out.println("product: " + prod); Which of the following best describes the error in the program? A The variable prod is incorrectly initialized. B The while condition always evaluates to false. C The while condition always evaluates to true. D The negative number entered to signal no more input is included in the product. E If the user enters a zero, the computation of the product will be terminated prematurely.

D The negative number entered to signal no more input is included in the product.

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

D The sum of all odd integers between 1 and num, inclusive

Consider the following methods. /** Precondition: a > 0 and b > 0 */ public static int methodOne(int a, int b) { int loopCount = 0; for (int i = 0; i < a / b; i++) { loopCount++; } return loopCount; } /** Precondition: a > 0 and b > 0 */ public static int methodTwo(int a, int b) { int loopCount = 0; int i = 0; while (i < a) { loopCount++; i += b; } return loopCount; } Which of the following best describes the conditions under which methodOne and methodTwo return the same value? A When a and b are both even B When a and b are both odd C When a is even and b is odd D When a % b is equal to zero E When a % b is equal to one

D When a % b is equal to zero

Assume obj1 and obj2 are object references. Which of the following best describes when the expression obj1 == obj2 is true? A When obj1 and obj2 are defined within the same method B When obj1 and obj2 are instances of the same class C When obj1 and obj2 refer to objects that contain the same data D When obj1 and obj2 refer to the same object E When obj1 and obj2 are private class variables defined in the same class

D When obj1 and obj2 refer to the same object

Consider the following code segment. String temp = "comp"; System.out.print(temp.substring(0) + " " + temp.substring(1) + " " + temp.substring(2) + " " + temp.substring(3)); What is printed when the code segment is executed? A comp B c o m p C comp com co c D comp omp mp p E comp comp comp comp

D comp omp mp p

Consider the following code segment. String alpha = new String("APCS"); String beta = new String("APCS"); String delta = alpha; System.out.println(alpha.equals(beta)); System.out.println(alpha == beta); System.out.println(alpha == delta); What is printed as a result of executing the code segment? A false false false B false false true C true false false D true false true E true true true

D true false true

Consider the following code segment. 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? A. -1.0 B. -0.5 C. 0.0 D. 0.5 E. 1.0

D. 0.5

Consider the following code segment. String str = "0"; str += str + 0 + 8; System.out.println(str); What is printed as a result of executing the code segment? A. 8 B. 08 C. 008 D. 0008 E. Nothing is printed, because numerical values cannot be added to a String object.

D. 0008

Consider the following code segment. String str = "a black cat sat on a table"; int counter = 0; for (int i = 0; i < str.length() - 1; i++) { if (str.substring(i, i + 1).equals("a") && !str.substring(i + 1, i + 2).equals("b")) { counter++; } } System.out.println(counter); What is printed as a result of executing this code segment? A. 1 B. 2 C. 3 D. 5 E. 6

D. 5

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? A. 2 B. 6 C. 8 D. 9 E. 14

D. 9

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

D. II and 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? A. There is no error, and the code works as intended. B. 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 even values of sum. C. In the expression (double) (sum / 2), the cast to double is applied too late, so the average will be greater than the expected result for even values of sum. D. 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. E. In the expression (double) (sum / 2), the cast to double is applied too late, so the average will be greater than the expected result for odd values of sum.

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

D. return (days * dailyRate) + (miles * mileageRate);

Consider the following method, between, which is intended to return true if x is between lower and upper, inclusive, and false otherwise. // precondition: lower <= upper // postcondition: returns true if x is between lower and upper, // inclusive; otherwise, returns false public boolean between(int x, int lower, int upper) { /* missing code */ } Which of the following can be used to replace /* missing code */ so that between will work as intended? A. return (x <= lower) && (x >= upper); B. return (x <= lower) || (x >= upper); C. return lower <= x <= upper; D. return (x >= lower) && (x <= upper); E. return (x >= lower) || (x <= upper);

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

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

E 2 + (int) (Math.random() * 6) + (int) (Math.random() * 6)

Consider the following code segments. I. int k = 1; while (k < 20) { if (k % 3 == 1) System.out.print( k + " "); k = k + 3; } II. for (int k = 1; k < 20; k++) { if (k % 3 == 1) System.out.print( k + " "); } III. for (int k = 1; k < 20; k = k + 3) { System.out.print( k + " "); } Which of the code segments above will produce the following output? 1 4 7 10 13 16 19 A I only B II only C I and II only D II and III only E I, II, and III

E I, II, and III

Assume that a, b, and c are variables of type int. Consider the following three conditions. I. (a == b) && (a == c) && (b == c) II. (a == b) || (a == c) || (b == c) III. ((a - b) * (a - c) * (b - c)) == 0 Assume that subtraction and multiplication never overflow. Which of the conditions above is (are) always true if at least two of a, b, and c are equal? A I only B II only C III only D I and II E II and III

E II and III

Consider the following two code segments. Code segment II is a revision of code segment I in which the loop header has been changed. I. for (int k = 1; k <= 5; k++) { System.out.print(k); } II. for (int k = 5; k >= 1; k--) { System.out.print(k); } Which of the following best explains how the output changes from code segment I to code segment II? A Both code segments produce the same output, because they both iterate four times. B Both code segments produce the same output, because they both iterate five times. C Code segment I prints more values than code segment II does, because it iterates for one additional value of k. D Code segment II prints more values than code segment I, because it iterates for one additional value of k. E The code segments print the same values but in a different order, because code segment I iterates from 1 to 5 and code segment II iterates from 5 to 1.

E The code segments print the same values but in a different order, because code segment I iterates from 1 to 5 and code segment II iterates from 5 to 1.

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? A The getPopulation method should be declared as private. B The return type of the getPopulation method should be void. C The getPopulation method should have at least one parameter. D The variable population is not declared inside the getPopulation method. E The instance variable population should be returned instead of p, which is local to the constructor.

E The instance variable population should be returned instead of p, which is local to the constructor.

Consider the following class definition. public class Password { private String password; public Password (String pwd) { password = pwd; } public void reset(String new_pwd) { password = new_pwd; } } Consider the following code segment, which appears in a method in a class other than Password. The code segment does not compile. Password p = new Password("password"); System.out.println("The new password is " + p.reset("password")); Which of the following best identifies the reason the code segment does not compile? A The code segment attempts to access the private variable password from outside the Password class. B The new password cannot be the same as the old password. C The Password class constructor is invoked incorrectly. D The reset method cannot be called from outside the Password class. E The reset method does not return a value that can be printed.

E The reset method does not return a value that can be printed.

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? A The variable numGallons is not declared in the getNumGallons method. B The variable saltWater is not declared in the isSaltWater method. C The isSaltWater method does not return the value of an instance variable. D The value returned by the getNumGallons method is not compatible with the return type of the method. E The value returned by the isSaltWater method is not compatible with the return type of the method.

E The value returned by the isSaltWater method is not compatible with the return type of the method.

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

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

Consider the following statement. Assume that a and b are properly declared and initialized boolean variables. boolean c = (a && b) || (!a && b); Under which of the following conditions will c be assigned the value false ? A Always B Never C When a and b have the same value D When a has the value false E When b has the value false

E When b has the value false

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

E balance = balance + amount; return balance;

Consider the following code segment. for (int k = 1; k <= 7; k += 2) { System.out.print(k); } Which of the following code segments will produce the same output as the code segment above? A for (int k = 0; k < 7; k += 2) { System.out.print(k); } B for (int k = 0; k <= 7; k += 2) { System.out.print(k); } C for (int k = 0; k <= 8; k += 2) { System.out.print(k + 1); } D for (int k = 1; k < 7; k += 2) { System.out.print(k + 1); } E for (int k = 1; k <= 8; k += 2) { System.out.print(k); }

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

Consider the following code segment. if (a < b || c != d) { System.out.println("dog"); } else { System.out.println("cat"); } Assume that the int variables a, b, c, and d have been properly declared and initialized. Which of the following code segments produces the same output as the given code segment for all values of a, b, c, and d ? A if (a < b && c != d) { System.out.println("dog"); } else { System.out.println("cat"); } B if (a < b && c != d) { System.out.println("cat"); } else { System.out.println("dog"); } C if (a > b && c == d) { System.out.println("cat"); } else { System.out.println("dog"); } D if (a >= b || c == d) { System.out.println("cat"); } else { System.out.println("dog"); } E if (a >= b && c == d) { System.out.println("cat"); } else { System.out.println("dog"); }

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

The Student class has been defined to store and manipulate grades for an individual student. The following methods have been defined for the class. /* Returns the sum of all of the student's grades */ public double sumOfGrades() { /* implementation not shown */ } /* Returns the total number of grades the student has received */ public int numberOfGrades() { /* implementation not shown */ } /* Returns the lowest grade the student has received */ public double lowestGrade() { /* implementation not shown */ } Which of the following statements, if located in a method in the Student class, will determine the average of all of the student's grades except for the lowest grade and store the result in the double variable newAverage ? A newAverage = sumOfGrades() / numberOfGrades() - 1; B newAverage = sumOfGrades() / (numberOfGrades() - 1); C newAverage = sumOfGrades() - lowestGrade() / (numberOfGrades() - 1); D newAverage = (sumOfGrades() - lowestGrade()) / numberOfGrades() - 1; E newAverage = (sumOfGrades() - lowestGrade()) / (numberOfGrades() - 1);

E newAverage = (sumOfGrades() - lowestGrade()) / (numberOfGrades() - 1);

Assume that a, b, and c are boolean variables that have been properly declared and initialized. Which of the following boolean expressions is equivalent to !(a && b) || c ? A. a && b && c B. a || b || c C. !a && !b || c D. !a && !b && c E. !a || !b || c

E. !a || !b || c

Consider the following code segment. String str = "CompSci"; System.out.println(str.substring(0, 3)); int num = str.length(); What is the value of num when the code segment is executed? A. 3 B. 4 C. 5 D. 6 E. 7

E. 7

Consider the following class definition. public class Element { public static int max_value = 0; private int value; public Element (int v) { value = v; if (value > max_value) { max_value = value; } } } The following code segment appears in a class other than Element. for (int i = 0; i < 5; i++) { int k = (int) (Math.random() * 10 + 1); if (k >= Element.max_value) { Element e = new Element(k); } } Which of the following best describes the behavior of the code segment? A. Exactly 5 Element objects are created. B. Exactly 10 Element objects are created. C. Between 0 and 5 Element objects are created, and Element.max_value is increased only for the first object created. D. Between 1 and 5 Element objects are created, and Element.max_value is increased for every object created. E. Between 1 and 5 Element objects are created, and Element.max_value is increased for at least one object created.

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

Consider the following method, which is intended to calculate and return the expression sqrt((x+y)^2/|a-b|). 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? A. Math.sqrt(x ^ 2, y ^ 2, a - b) B. Math.sqrt((x + y) ^ 2) / Math.abs(a, b) C. Math.sqrt((x + y) ^ 2 / Math.abs(a - b)) D. Math.sqrt(Math.pow(x + y, 2) / Math.abs(a, b)) E. Math.sqrt(Math.pow(x + y, 2) / Math.abs(a - b))

E. Math.sqrt(Math.pow(x + y, 2) / Math.abs(a - b))

Consider the following static method. public static int calculate(int x) { x = x + x; x = x + x; x = x + x; return x; } Which of the following can be used to replace the body of calculate so that the modified version of calculate will return the same result as the original version for all x ? A. return 3 + x; B. return 3 * x; C. return 4 * x; D. return 6 * x; E. return 8 * x;

E. return 8 * x;

Consider the following method that is intended to determine if the double values d1 and d2 are close enough to be considered equal. For example, given a tolerance of 0.001, the values 54.32271 and 54.32294 would be considered equal. /** @return true if d1 and d2 are within the specified tolerance, false otherwise */ public boolean almostEqual (double d1, double d2, double tolerance) { /*missing code*/} Which of the following should replace / * missing code * / so that almostEqual will work as intended? A. return (d1 - d2) <= tolerance; B. return ((d1 + d2) / 2) <= tolerance; C. return (d1 - d2) >= tolerance; D. return ( (d1 + d2) / 2) >= tolerance; E. return Math.abs(d1 - d2) <= tolerance;

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


Related study sets

Chapter 24: Parathyroid and Adrenal Disorders

View Set

PA Accident and Health Insurance

View Set

CompTIA Security+ Exam SY0-501 Common Vulnerabilities

View Set

Health Assessment - Prepu Cha. 24

View Set

Chapter 16: Publicity: Promotion Using Earned Media, Owned Media, and Social Media

View Set

Maternity Prep U Practice -Postpartum & Pregnancy Complications

View Set

Macroeconomics Chapter 11 practice/review Part 2

View Set