AP Computer Science Midterm

Ace your homework & exams now with Quizwiz!

int a = 10, b = 3, t; for (int i=1; i<=6; i++) { t = a; a = i + b; b = t - i; }

a = 13 and b = 0 The variable i loops from 1 to 6 i = 1, t = 10, a = 4, b = 9 i = 2, t = 4, a = 11, b =2 i = 3, t = 11, a = 5, b = 8 i = 4, t = 5, a = 12, b = 1 i = 5, t = 12, a = 6, b = 7 i = 6, t = 6, a = 13, b = 0

private int[] numArray; public int getRunSize() { if (numArray.length == 0) return 0; int size = 1; while ((size < numArray.length) && (numArray[size - 1] > numArray[size])) { size++; } // assertion return size; }

(size == numArray.length) || (numArray[size - 1] <= numArray[size]) The while loop continues as long as the value of size is less than the number of elements in numArray and the value in numArray at an index of one less than size is greater than the value at numArray with an index of size. So if the loop stopped either the value in size equals the number of elements in the numArray or the value at the index size - 1 in numArray is less than or equal to the value at index size in numArray.

public int m1(int[] a) { a[1]--; return (a[1] * 2); } If int[] a = {8, 3, 1}, what is the value in a[1] after m1(a); is run?

2 The statement a[1]--; is the same as a[1] = a[1] - 1; so this will change the 3 to a 2. The return (a[1] * 2) does not change the value at a[1].

for (int k = 0; k < 20; k = k + 2) { if (k % 3 == 1) System.out.print(k + " "); }

4 10 16 This will loop with k having a value of 0 to 18 (it will stop when k = 20). It will print out the value of k followed by a space when the remainder of dividing k by 3 is 1.

public class Base { public void methodOne() { System.out.print("A"); methodTwo(); } public void methodTwo() { System.out.print("B"); } } public class Derived extends Base { public void methodOne() { super.methodOne(); System.out.print("C"); } public void methodTwo() { super.methodTwo(); System.out.print("D"); } } Assume that the following declaration appears in a client program. Base b = new Derived();

ABDC Even though b is declared as type Base it is created as an object of the Derived class, so all methods to it will be resolved starting with the Derived class. So the methodOne() in Derived will be called. This method first calls super.methodOne so this will invoke the method in the superclass (which is Base). So next the methodOne in Base will execute. This prints the letter "A" and invokes this.methodTwo(). Since b is really a Derived object, we check there first to see if it has a methodTwo. It does, so execution continues in Derived's methodTwo. This method invokes super.methodTwo. So this will invoke the method in the super class (Base) named methodTwo. This method prints the letter "B" and then returns. Next the execution returns from the call to the super.methodTwo and prints the letter "D". We return to the Base class methodOne and return from that to the Derived class methodOne and print the letter "C". Derived methodOne Base methodOne print "A" Derived methodTwo Base methodTwo print "B" return to derived methodTwo print "D" return to derived methodOne print "C"

Which of the following is a reason to use an ArrayList instead of an array?

An ArrayList resizes itself as necessary as items are added, but an array does not. Yes, an ArrayList is really a dynamic array (one that can grow or shrink as needed). When an ArrayList is full and you try to add another item a new larger array is created and all items are copied from the original array. The new array is typically 2 times as large as the original.

Which of the following code sequences can be used to replace lines 3-5 in the code below to correctly search a String array for the first identical match of the characters in wordToFind, and return the array index where it was found or -1 if it was not found? 1. public static int linearFind(String[] array, String wordToFind) { 2. int index = 0; 3. while() { 4. } 5. if () { 6. } 7. else { 8. return(-1); 9. } 10. }

Answer a: while (!(array[index].equals(wordToFind)) && (index < array.length)) { index++; } if (index < array.length) { return index; While the string at this index in the array isn't equal to wordToFind and the index is less than the length of the array then increment the index. After the while loop check if the reason the loop stopped is because the string was found by checking if the index is still less than the length of the array. If the string wasn't found this loop will continue until index equals the length of the array.

for (int j = 1; j < 5; j++) { for (int k = 1; k <= 5; k++) System.out.print(j * k + " "); System.out.println(); }

Answer a: 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 The variable j loops from 1 to 4 and k loops from 1 to 5 (k <= 5) and each time in the inner loop it prints j * k and after the inner loop it will print a new line. for j=1; 1*1 1*2 1*3 1*4 1*5 for j=2; 2*1 2*2 2*3 2*4 2*5 for j=3; 3*1 3*2 3*3 3*4 3*5 for j=4; 4*1 4*2 4*3 4*4 4*5

I. One interface can inherit from another. II. You can declare a abstract method in an interface. III. You can create a new object using an interface. If I have an interface named List I can do List aList = new List();

I and II only I and II are both true. III is false. You can't use the new operator with an interface name. You can declare variables to be of an interface type. You could say List aList = new ArrayList();

public class Book { public String getISBN() { // implementation not shown } // constructors, fields, and other methods not shown } public class Dictionary extends Book { public String getDefinition(String word) { // implementation not shown } // constructors, fields, and methods not shown } Assume that the following declaration appears in a client class. Book b = new Dictionary(); Which of the following statements would compile without error? I. b.getISBN(); II. b.getDefinition("wonderful"); III. ((Dictionary) b).getDefinition("wonderful");

I and III only I is correct because variable b has been declared to be an object of the class Book so you can invoke any public methods that are defined in the book class or in parents of Book. II is not correct because you can't invoke methods in the Dictionary class directly on b since b is declared to be of type Book not type Dictionary and Dictionary is a subclass of Book not a parent class of Book. III is correct because you can cast b to type Dictionary and then invoke public methods in Dictionary.

public class Point2D { public int x; public int y; public Point2D() {} public Point2D(int x,int y) { this.x = x; this.y = y; } // other methods } public class Point3D extends Point2D { public int z; // other code } Which of the following constructors would be valid for Point3D? I. public Point3D() {} II. public Point3D(int x, int y, int z) { super(x,y); this.z = z; } III. public Point3D(int x, int y) { this.x = x; this.y = y; this.z = 0; }

I, II, and III I is true because Point2D does have a no-arg constructor. II is true because Point2D does have a constructor that takes x and y. III is true because Point2D does have a no-arg constructor which will be called before the first line of code is executed in this constructor. The fields x and y are public in Point2D and thus can be directly accessed by all classes.

String s1 = "xyz"; String s2 = s1; String s3 = s2; After this code is executed, which of the following statements will evaluate to TRUE? I. s1.equals(s3) II. s1 == s2 III. s1 == s3

I,II, and III This is correct, as the "equals" operation is overloaded for use with strings, so I is true. II and III are both true because the code as written assigns both s2 and s3 to the same object as s1.

In the GridWorld Case Study which of the following is an interface or which of the following are interfaces? I. Actor II. Grid III. Location IV. Direction

II only Only Grid is an interface. Actor and Location are classes. In the GridWorld Case Study the direction the actor is facing is just an integer field in the Actor class. The Location class also has some constants for the cardinal directions.

public class Person implements Comparable { private String firstName; private String lastName; public int compareTo(Object test) { // implementation not shown } // constructors, other fields, and methods not shown } Assume that the Person objects are ordered by last name and then first name. Which of the following will correctly implement compareTo for the Person class?

III only Number I will give strange results since you add the result of the compare of the first and last names. It can give a result of 0 when a compare of the first name returns a positive number of value x and a compare of the last name returns a negative number of value x. Number II would be correct if we were ordering on first name and then last name. Number III is correct. It compares the last names and if they don't match returns the result of that comparison and if they do match returns the result of comparing the first names.

We want to create a ChameleonCrabCritter which will act like a CrabCritter but will also change color (like a ChameleonCritter) to that of one of the neighbors directly in front, diagonal left in front, or diagonal right in front (the ones a CrabCritter will eat if they aren't rocks or critters). In each of the following designs, assume that ChameleonCrabCritter has all the needed constructors, fields, and methods. Which design(s) are good? I. ChameleonCrabCritter extends Critter 1) Copy all the methods in CrabCritter to ChameleonCrabCritter 2) Override the processActors method to first pick a random neighbor from the passed in ones and set the critters color to that neighbor's color and then call super.processActors to eat the neighbors that aren't rocks or critters. II. ChameleonCrabCritter extends ChameleonCritter 1) Copy all the methods in CrabCritter to ChameleonCrabCritter 2) Modify processActors to call super.processActors to change the color to one of the neighbors and then also eat the neighbors that aren't rocks or critters by removing them from the grid. III. ChameleonCrabCritter extends CrabCritter 1) Copy the processActors method from ChameleonCritter to ChameleonCrabCritter but add a super.processActors() at the end to eat the neighbors that aren't rocks or critters.

III only. If a ChameleonCrabCritter has most of the same behavior as a CrabCritter then it makes the most sense to inherit from CrabCritter. All that needs to be added is the changing of the color to one of the neighbors which can be handled by copying the processActors method from ChameleonCritter and modifying it to add super.processActors() at the end of the method to eat the neighbors that aren't rocks or critters.

We want to define a new class SlowCritter that extends Critter. An object of this new class should move like a Critter except that it will only have a 50% chance of moving if it can move. Which of the following methods should this class override? I. act II. getActors III. makeMove IV. getMoveLocations

III only. The makeMove method is where the move takes place as long as the passed location isn't null. This should be changed to move only if the result of Math.random() is less than 0.5. public void makeMove(Location loc) { if (loc == null) removeSelfFromGrid(); else if (Math.random() < 0.5) moveTo(loc); }

public boolean checkID (int id, String name, Student nextStudent) { if ((nextStudent.getName()).equals(name) && id == nextStudent.getID()) return true; else { id = nextStudent.getID(); nextStudent.setID(0); nextStudent.setName("VACANT"); return false; } }

If you modify a primitive type parameter in Java in a method it will not change the value of the variable in the calling method. Java uses pass by value for parameters. So when you pass a variable to a method it will make a new variable that is only known in that method and assign its value to a copy of the original value. So if you pass in a variable j that has the value 4 a new variable id is created and its value is set to 4. Any changes to id will not affect the value of j If you pass an object reference to a method then a copy of the reference is made. So any changes you make to the object will persist.

public void sort() 0: { 1: for (int i = 1; i < a.length; i++) 2: { 3: int next = a[i]; 4: // Move all larger elements to the right 5: int j = i; 6: while (j > 0 && a[j - 1] > next) 7: { 8: a[j-1] = a[j]; 9: j--; 10: } 11: // Insert the element 12: a[j] = next; 13: } 14: } However, it does not work properly. Which is the line that contains an error?

In line 8 it should be a[j] = a[j-1]; Larger elements of the array should be shifted to the right (toward the back) of the array. The statement a[j-1] = a[j] shifts the element to the front, which is the opposite of what needs to be done.

Consider the following data field and method findLongest with line numbers added for reference. Method findLongest is intended to find the longest consecutive block of the value target occurring in the array nums; however, findLongest does not work as intended. For example, if the array nums contains the values [7, 10, 10, 15, 15, 15, 15, 10, 10, 10, 15, 10, 10], the call findLongest(10) should return 3, the length of the longest consecutive block of 10s. private int[] nums; public int findLongest(int target) { int lenCount = 0; int maxLen = 0; Line 1: for (int k = 0; k < nums.length; k++) Line 2: { Line 3: if (nums[k] == target) Line 4: { Line 5: lenCount++; Line 6: } Line 7: else Line 8: { Line 9: if (lenCount > maxLen) Line 10: { Line 11: maxLen = lenCount; Line 12: } Line 13: } Line 14: } Line 15: if (lenCount > maxLen) Line 16: { Line 17: maxLen = lenCount; Line 18: } Line 19: return maxLen; }

Insert the statement lenCount = 0; between lines 12 and 13. The test of nums[k] == target has failed so we no longer have a run of the target values and we need to reset lenCount. This goes here so that it happens regardless of if (lenCount > maxLen) and it is after the saving of this length if it is the longest consecutive block of target values.

public static void selectionSort(int[] numberArray) { int temp; // used to hold value for (int i = 0; i < numberArray.length - 1; i++) // line 1 { int pos = i; // line 2 for (int j = 0; j < numberArray.length; j++) // line 3 { if (numberArray[j] < numberArray[pos]) // line 4 { pos = j; // line 5 } } temp = numberArray[i]; numberArray[i] = numberArray[pos]; numberArray[pos] = temp; } } This

Line 3 should be: for (int j = i + 1; j < numberArray.length; j++) A selection sort is supposed to loop through the array from 0 to length - 2 and each time find the smallest value in the rest of the array (starting with i+1) and exchange it with the value at position i. The current code only puts the smallest value at index length - 2.

Which one of the following statements about method overloading and overriding is true?

Overriding allows for polymorphism which means that the actual method that gets called at runtime depends on the type of the object at runtime. Overriding allows a child class to define a method with the same name and method signature as a parent class. The child method will be called instead of the parent method. This allows inheritance-based polymorphism since the method called at runtime will depend on the type of the object.

public class Person implements Comparable { code for class including a compareTo() method } public class Player extends Person { code for class } Which declaration will result in a compiler error?

Player p = new Person(); A variable can hold the declared type and any child of that type. The class Person is not a child of the class Player so this is not allowed and will not compile.

Under which of these conditions is it appropriate to overload a method (ie: the class will contain two methods with the same name)

The methods have different numbers of parameters Correct, overloading is necessary is when two functions that perform the same essential operation take a different number of parameters.

Under which of these conditions will a sequential search be faster than a binary search?

The search value is the first element in the array. Correct, Only when the search value is the first item in the array, and thus the first value encountered in sequential search, will sequential be faster than binary.

Which will cause the longest execution of a sequential search looking for a value in an array of 10 integers?

The value is not in the array If the value is not in the array it will have to check every element in the array to be sure that it is not in the array. This takes n executions of the loop for n items in the array.

Which of the following best describes the purpose of a methods pre and post conditions?

They provide information to the programmer about what the method is intended to do. Correct, Pre conditions define the state before a method is executed, and Post conditions define what the state is after the execution.

Assume that x is an initialized int variable. The code segment: if (x > 2) x *= 2; if (x > 4) x = 0; is equivalent to which of the following code segments?

if (x > 2) x = 0; If x > 2, say 3, the first if will reset x so it will be then also be greater than 4. Thus, whenever x is greater than 2, both if will be true, and x will be set to 0.

Consider the following declaration that appears in a client program: TimeRecord[] timeCards = new TimeRecord[100]; Assume that timeCards has been initialized with TimeRecord objects. Consider the following code segment that is intended to compute the total of all the times stored in timeCards. TimeRecord total = new TimeRecord(0,0); for (int k = 0; k < timeCards.length; k++) { /* missing expression */ ; } Which of the following can be used to replace /* missing expression */ so that the code segment will work as intended?

total.advance(timeCards[k].getHours(), timeCards[k].getMinutes()) This will add each current time card hours and minutes to the total.

int var1 = 0; int var2 = 2; while ((var2 != 0) && ((var1 / var2) >= 0)) { var1 = var1 + 1; var2 = var2 - 1; }

var1=2, var2=0 The loop starts with var1=0 and var2=2. The while checks that var2 isn't 0 (2!=0) and that var1 / var2 is greater than or equal to zero (0/2=0) so this is equal to zero and the body of the while loop will execute. The variable var1 has 1 added to it for a new value of 1. The variable var2 has 1 subtracted from it for a value of 1. At this point var1=1 and var2=1. The while condition is checked again. Since var2 isn't 0 (1!=0) and var1/var2 (1/1=1) is >= 0 so the body of the loop will execute again. The variable var1 has 1 added to it for a new value of 2. The variable var2 has 1 subtracted from it for a value of 0. At this point var1=2 and var2=0. The while condition is checked again. Since var2 is zero the while loop stops and the value of var1 is 2 and var2 is 0.

String s1 = "xy"; String s2 = s1; s1 = s1 + s2 + "z";

xyxyz Correct, s1 contains the original value, plus itself, plus "z"


Related study sets

Weak Points: AWS Cost Management

View Set

Spanish II SPEAKING EXAM: 105-133

View Set