AP Computer Science A, AP Computer Science A, AP Computer Science A

Ace your homework & exams now with Quizwiz!

Consider the following class definitions. public class Bike { private int numWheels = 2; // No constructor defined } public class EBike extends Bike { private int numBatteries; public EBike(int batteries) { numBatteries = batteries; } } The following code segment appears in a method in a class other than Bike or EBike. EBike eB = new EBike(4); Which of the following best describes the effect of executing the code segment?

A. An implicit call to the zero-parameter Bike constructor initializes the instance variable numWheels. The instance variable numBatteries is initialized using the value of the parameter batteries.

What logical operator does the following truth table correspond to? ? | T ----------- T | F F | T

!

What logical operator does the following truth table correspond to? ? | T F -------------- T | T F F | F F

&&

Consider the following class definitions. public class Robot { private int servoCount; public int getServoCount() { return servoCount; } public void setServoCount(int in) { servoCount = in; } } public class Android extends Robot { private int servoCount; public Android(int initVal) { setServoCount(initVal); } public int getServoCount() { return super.getServoCount(); } public int getLocal() { return servoCount; } public void setServoCount(int in) { super.setServoCount(in); } public void setLocal(int in) { servoCount = in; } } The following code segment appears in a method in another class. int x = 10; int y = 20; /* missing code */ Which of the following code segments can be used to replace /* missing code */ so that the value 20 will be printed?

A. Android a = new Android(x); a.setServoCount(y); System.out.println(a.getServoCount());

Consider the following class declarations. public class Hat { private String size; public Hat(String s) { size = s; } public String toString() { return "Size " + size + " hat"; } } public class BallCap extends Hat { private String team; public BallCap(String mySize, String myTeam) { super(mySize); team = myTeam; } public String toString() { return super.toString() + " with " + team + " logo"; } } A code segment located in a different class is intended to produce the following output. Size L hat with Denver logo Which of the following code segments will produce this output?

A. BallCap myHat = new BallCap("L", "Denver"); System.out.println(myHat);

Consider the following code segment. System.out.print("Ready"); // Line 1 System.out.print("Set"); // Line 2 System.out.print("Go!"); // Line 3 The code segment is intended to produce the following output but may not work as intended. Ready Set Go! Which change, if any, can be made so that the code segment produces the intended output?

A. Changing print to println in lines 1 and 2

Consider the following two code segments. Assume that variables x and y have been declared as int variables and have been assigned integer values. I. int result = 0; if (x > y) { result = x - y; System.out.print(result); } else if (x < y) { result = y - x; System.out.print(result); } else { System.out.print(result); } II. if (x < y) { System.out.print(y - x); } else { System.out.print(x - y); } Which of the following correctly compares the outputs of the two code segments?

A. Code segment I and code segment II produce the same output for all values of x and y.

Each of the following code segments is intended to print the word Hello. Which of the following code segments works as intended? I. System.out.print("Hello"); II. System.out.print(Hello); III. System.out.print(He); System.out.print(llo);

A. I only

In the code segment below, the int variable temp represents a temperature in degrees Fahrenheit. The code segment is intended to print a string based on the value of temp. The following table shows the string that should be printed for different temperature ranges. Temperature RangeString to Print31 and below"cold"32-50"cool"51-70"moderate"​71 and above"warm" String weather; if (temp <= 31) { weather = "cold"; } else { weather = "cool"; } if (temp >= 51) { weather = "moderate"; } else { weather = "warm"; } System.out.print(weather); Which of the following test cases can be used to show that the code does NOT work as intended? I. temp = 30 II. temp = 51 III. temp = 60

A. I only

Consider the class definition below. The method levelUp is intended to increase a Superhero object's strength attribute by the parameter amount. The method does not work as intended. public class Superhero { private String name; private String secretIdentity; private int strength; public Superhero(String realName, String codeName) { name = realName; secretIdentity = codeName; strength = 5; } public int levelUp(int amount) // line 14 { strength += amount; // line 16 } } Which of the following changes should be made so that the levelUp method works as intended?

A. In line 14, levelUp should be declared as type void.

Consider the following method countNegatives, which searches an ArrayList of Integer objects and returns the number of elements in the list that are less than 0. public static int countNegatives(ArrayList<Integer> arr) { int count = 0; for (int j = 0; j < arr.size(); j++) // Line 4 { if (arr.get(j) < 0) { count++; } } return count; } Which of the following best explains the impact to the countNegatives method when, in line 4, j < arr.size() is replaced with j <= arr.size() - 1 ?

A. It has no impact on the behavior of the method.

Consider the following class definitions. public class First { public void output1() { output2(); } public void output2() { output3(); } public void output3() { System.out.print("First"); } } public class Second extends First { public void output() { output1(); output2(); output3(); } } public class Third extends Second { public void output3() { System.out.print("Third"); } } The following code segment appears in a class other than First, Second, or Third. First sec = new Second(); // Line 1 Second thr = new Third(); // Line 2 sec.output(); // Line 3 thr.output(); // Line 4 Which of the following best explains why the code segment will not compile?

A. Line 3 causes a compile-time error because the variable sec should be declared as type Second.

Consider the following class definition. public class Document { private int pageCount; private int chapterCount; public Document(int p, int c) { pageCount = p; chapterCount = c; } public String toString() { return pageCount + " " + chapterCount; } } The following code segment, which is intended to print the page and chapter counts of a Document object, appears in a class other than Document. Document d = new Document(245, 16); System.out.println( /* missing code */ ); Which of the following can be used as a replacement for /* missing code */ so the code segment works as intended?

A. d.toString()

A teacher has created a Student class. The class contains the following. An int variable called grade to represent the student's grade level A String variable called name to represent the student's name A double variable called average to represent the student's grade point average A method called updateAverage that updates the student's average. The object greg will be declared as type Student. Which of the following descriptions is accurate?

A. greg is an instance of the Student class.

Consider the following expression. (3 + 4 == 5) != (3 + 4 >= 5) What value, if any, does the expression evaluate to?

A. true

Hashing Algorithm

An algorithm that calculates a unique number based on a key. That number is then used to determine the index where the data is stored.

2D Array

An array that holds a set of arrays. Its data is organized by rows and columns, and usually represents grids, tables, or matrices.

If you divide an integer by zero, what kind of error is thrown?

ArithmeticException

If you use a negative array index, what kind of error is thrown?

ArrayIndexOutOfBoundsException

Which can grow and shrink as needed in a program: an array or an ArrayList?

ArrayList

Which only needs a single statement to insert or delete elements: an array or an ArrayList?

ArrayList

In the following expression, j, k, and m are properly declared and initialized int variables. !((j == k) && (k > m)) Which of the following is equivalent to the expression above?

B. (j != k) || (k <= m)

In the following expression, sweet, salty, and sour are properly declared and initialized boolean variables. sweet && (salty || sour) Which of the following expressions is equivalent to the expression above?

B. (sweet && salty) || (sweet && sour)

Consider the following code segment. double d = 0.25; int i = 3; double diff = d - i; System.out.print((int)diff - 0.5); What is printed as a result of executing the code segment?

B. -2.5

Consider the following method. public void adjust(double max, double min, double total, double n) { total = total - max - min; n = n - 2.0; System.out.println(total / n); } Consider the call adjust(25.0, 5.0, 60.0, 5.0), which appears in a method in the same class. What is printed as a result of the method call?

B. 10.0

Consider the following method, which implements a recursive binary search. /** Returns an index in arr where the value x appears if x appears * in arr between arr[left] and arr[right], inclusive; * otherwise returns -1. * Precondition: arr is sorted in ascending order. * left >= 0, right < arr.length, arr.length > 0 */ public static int bSearch(int[] arr, int left, int right, int x) { if (right >= left) { int mid = (left + right) / 2; if (arr[mid] == x) { return mid; } else if (arr[mid] > x) { return bSearch(arr, left, mid - 1, x); } else { return bSearch(arr, mid + 1, right, x); } } return -1; } The following code segment appears in a method in the same class as bSearch. int[] nums = {0, 4, 4, 5, 6, 7}; int result = bSearch(nums, 0, nums.length - 1, 4); What is the value of result after the code segment has been executed?

B. 2

What is the formula to produce a random real value in the range lowValue<=x<highValue?

(highValue - lowValue) * Math.random() + lowValue;

Provide code to find a random integer in the range [0,99].

(int) (Math.random() * 100)

Provide code to find a random integer in the range [1,100].

(int) (Math.random() * 100) + 1

What is the concatenation operator?

+

Consider the following method. /* missing precondition */ public void someMethod(int j, int k, String oldString) { String newString = oldString.substring(j, k); System.out.println("New string: " + newString); } Which of the following is the most appropriate precondition for someMethod so that the call to substring does not throw an exception?

/* Precondition: 0 <= j <= k <= oldString.length() */

When an array with doubles or ints is declared, what are the values automatically initialized to?

0

What does compareTo return in the Integer class? ex: int compareTo(Integer other)

0 if the Integer is equal to other, negative if it's less than other, and positive if it's greater than other

A Java program must have at least ___ class(es).

1

Java primitive data types

1) double 2) int 3) float 4) long 5) short 6) boolean 7) byte 8) char

Provide code to find a random real value in the range [4.0,6.0).

2 * Math.random() + 4

Provide code to find a random real value in the range [0.0,6.0).

6 * Math.random();

The default implementation of equals() is equivalent to what operator?

==

identity operator

==; tests whether its operands are the same

ArrayList

A dynamic array that change adjust its size by easily adding and removing objects to the array

super

A keyword in java which is used to refer to the immediate parent class object.

What is a recursive method?

A method that calls itself

recursion

A programming technique in which a method will call itself to solve a problem. It breaks down the problem into similar sub-problems of the same format.

Merge Sort

A recursive algorithm that divides the input array each time the method is called. It will divide the array completely, put the data in order, and then merge the array back together.

insertion sort

A simple sorting algorithm that builds the final sorted array one item at a time. It essentially inserts the current number into the appropriate spot in the sorted section of the array.

selection sort

A sorting algorithm that divides the array into two parts: sorted and unsorted. It will swap array values to find the min value and move it to the sorted part of the array.

Define abstract class.

A superclass that represents an abstract concept, and is not instantiated

The method addItUp(m, n) is intended to print the sum of the integers greater than or equal to m and less than or equal to n. For example, addItUp(2, 5) should return the value of 2 + 3 + 4 + 5. /* missing precondition */ public static int addItUp(int m, int n) { int sum = 0; for (int j = m; j <= n; j++) { sum += j; } return sum; } Which of the following is the most appropriate precondition for the method?

A. /* Precondition: m <= n */

In the following code segment, assume that the ArrayList data has been initialized to contain the Integer values [4, 3, 4, 5, 3, 4]. int j = 0; while (j < data.size() - 1) { if (data.get(j) > data.get(j + 1)) { System.out.print(data.get(j + 1) + " "); } j++; } What, if anything, is printed as a result of executing the code segment?

A. 3 3

In the code segment below, numList is an ArrayList of integers that is sorted in descending order. The code segment is intended to insert the integer value val into numList so that numList is still sorted in descending order. int j = 0; while (val != numList.get(j)) { j++; } numList.add(j, val); The code segment does not always work as intended. Assuming that numList has been initialized to {3, 2, 1, 0}, for which value of val does the code segment NOT produce the expected result?A

A. 4

Consider the following code segment. ArrayList<String> arrList = new ArrayList<String>(); arrList.add("A"); arrList.add("B"); arrList.add("C"); arrList.add("D"); for (int i = 0; i < arrList.size(); i++) { System.out.print(arrList.remove(i)); } What, if anything, is printed as a result of executing the code segment?

A. AC

Consider the following method, which implements a recursive binary search. /** Returns an index in arr where the value x appears if x appears * in arr between arr[left] and arr[right], inclusive; * otherwise returns -1. * Precondition: arr is sorted in ascending order. * left >= 0, right < arr.length, arr.length > 0 */ public static int bSearch(int[] arr, int left, int right, int x) { if (right >= left) { int mid = (left + right) / 2; if (arr[mid] == x) { return mid; } else if (arr[mid] > x) { return bSearch(arr, left, mid - 1, x); } else { return bSearch(arr, mid + 1, right, x); } } return -1; } The following code segment appears in a method in the same class as bSearch. int[] nums = {10, 20, 30, 40, 50}; int result = bSearch(nums, 0, nums.length - 1, 40); How many times will the bSearch method be called as a result of executing the code segment, including the initial call?

B. 2

Consider the following class definitions. public class Game { private String name; public Game(String n) { name = n; } // Rest of definition not shown } public class BoardGame extends Game { public BoardGame(String n) { super(n); } // Rest of definition not shown } The following code segment appears in a class other than Game or BoardGame. Game g1 = new BoardGame("checkers"); BoardGame g2 = new Game("chess"); ArrayList<Game> My_Games = new ArrayList(); My_Games.add(g1); My_Games.add(g2); Which of the following best explains why the code segment does not compile?

B. A Game object cannot be assigned to the BoardGame reference g2.

Consider the following method, inCommon, which takes two Integer ArrayList parameters. The method returns true if the same integer value appears in both lists at least one time, and false otherwise. public static boolean inCommon(ArrayList<Integer> a, ArrayList<Integer> b) { for (int i = 0; i < a.size(); i++) { for (int j = 0; j < b.size(); j++) // Line 5 { if (a.get(i).equals(b.get(j))) { return true; } } } return false; } Which of the following best explains the impact to the inCommon method when line 5 is replaced by for (int j = b.size() - 1; j > 0; j--) ?

B. After the change, the method will never check the first element in list b.

Consider the following code segment. int x = 4; int y = 6; x -= y; y += x; Which of the following best describes the behavior of the code segment?

B. Both the value of x and the value of y have been decreased.

Consider the following code segment, which is intended to display 6.0. double fact1 = 1 / 2; double fact2 = 3 * 4; double product = fact1 * fact2; System.out.println(product); Which of the following best describes the error, if any, in the code segment?

B. Either the numerator or the denominator of the fraction 1 / 2 should be cast as double.

Consider the following class declarations. public class ParentClass { public void wheelsOnTheBus() { System.out.println("round and round"); } } public class SubClass extends ParentClass { public void wheelsOnTheBus() { System.out.println("are flat"); } } public class SubSubClass extends ParentClass { public void wheelsOnTheBus() { // No methods defined } } The following code segment appears in a method in another class. obj.wheelsOnTheBus(); Under which of the following conditions will the code segment print "are flat" ? I. when obj has been declared as type ParentClass II. when obj has been declared as type SubClass III. when obj has been declared as type SubSubClass

B. II only

Consider the following class definition. public class Time { private int hours; private int minutes; public Time(int h, int m) { hours = h; minutes = m; } public boolean equals(Object other) { if (other == null) { return false; } Time t = (Time) other; return (hours * 60 + minutes == t.hours * 60 + t.minutes); } } The following code segment appears in a class other than Time. Time t1 = new Time(1, 10); Time t2 = new Time(0, 70); Which of the following statements will print true ? System.out.println(t1 == t2); System.out.println(t1.equals(t2)); System.out.println(equals(t1, t2);

B. II only

Consider the following class. public class MagicNumber { private int num; public MagicNumber() { num = 10; } public void displayNumber() { System.out.println(num); } public void add_2() { num = num + 2; } } When located in a method in a class other than MagicNumber, which of the following code segments will compile without error? I. MagicNumber.add_2();MagicNumber.displayNumber(); II. MagicNumber n1 = new MagicNumber(); n1.add_2();n1.displayNumber(); III. n2.add_2();n2.displayNumber();

B. II only

Consider the following code segment. int x = 10; int y = 20; /* missing code */ System.out.print(top / bottom); Which of the following replacements for /* missing code */ will cause an ArithmeticException to occur? I. int top = x - y;int bottom = y - x; II. int top = 2 * x;int bottom = y - top; III. int top = x + y;int bottom = 2 * top;

B. II only

Consider the following class declarations. public class Tree { private String treeVariety; public Tree() { treeVariety = "Oak"; } public Tree(String variety) { treeVariety = variety; } } public class DeciduousTree extends Tree { public DeciduousTree(String variety) { super(); } } public class EvergreenTree extends Tree { public EvergreenTree(String variety) { super(variety); } } The following code segment appears in a method in another class. DeciduousTree tree1 = new DeciduousTree("Maple"); EvergreenTree tree2 = new EvergreenTree("Fir"); Which of the following best describes the result of executing the code segment?

B. Object tree1 is created using the DeciduousTree constructor, which uses super to set tree1's treeVariety attribute to "Oak". Object tree2 is created using the EvergreenTree constructor, which uses super to set tree2's treeVariety attribute to "Fir".

Consider the following class declarations. public class Dog { private String name; public Dog() { name = "NoName"; } } public class Poodle extends Dog { private String size; public Poodle(String s) { size = s; } } The following statement appears in a method in another class. Poodle myDog = new Poodle("toy"); Which of the following best describes the result of executing the statement?

B. The Poodle variable myDog is instantiated as a Poodle. The instance variable size is initialized to "toy". An implicit call to the no-argument Dog constructor is made, initializing the instance variable name to "NoName".

Consider the following code segment. String str1 = new String("Happy"); String str2 = new String("Happy"); System.out.print(str1.equals(str2) + " "); System.out.print(str2.equals(str1) + " "); System.out.print(str1 == str2); What is printed as a result of executing the code segment?

B. true true false

Consider the following method, remDups, which is intended to remove duplicate consecutive elements from nums, an ArrayList of integers. For example, if nums contains {1, 2, 2, 3, 4, 3, 5, 5, 6}, then after executing remDups(nums), nums should contain {1, 2, 3, 4, 3, 5, 6}. public static void remDups(ArrayList<Integer> nums) { for (int j = 0; j < nums.size() - 1; j++) { if (nums.get(j).equals(nums.get(j + 1))) { nums.remove(j); j++; } } } The code does not always work as intended. Which of the following lists can be passed to remDups to show that the method does NOT work as intended?

B. {1, 2, 2, 3, 3, 4, 5}

b.

Book book1 = new Book("Frankenstein", "Mary Shelley"); Book book2 = new PictureBook("The Wonderful Wizard of Oz", "L. Frank Baum", "W.W. Winslow");

What are the four steps in Mergesort?

Break the array in two, mergesort the left half, mergesort the right half, then merge the two subarrays into one.

In the following expression, sunny and windy are properly declared and initialized boolean variables. !sunny && !windy Which of the following is equivalent to the expression above?

C. !(sunny || windy)

Consider the following correct implementation of the selection sort algorithm. public static void selectionSort(int[] elements) { for (int j = 0; j < elements.length - 1; j++) { int minIndex = j; for (int k = j + 1; k < elements.length; k++) { if (elements[k] < elements[minIndex]) { minIndex = k; } } if (j != minIndex) { int temp = elements[j]; elements[j] = elements[minIndex]; elements[minIndex] = temp; // line 19 } } } The following declaration and method call appear in a method in the same class as selectionSort. int[] arr = {30, 40, 10, 50, 20}; selectionSort(arr); How many times is the statement elements[minIndex] = temp; in line 19 of the method executed as a result of the call to selectionSort ?

C. 3

Consider the following class definitions. public class Road { private String roadName; public Road(String name) { roadName = name; } } public class Highway extends Road { private int speedLimit; public Highway(String name, int limit) { super(name); speedLimit = limit; } } The following code segment appears in a method in another class. Road r1 = new Highway("Interstate 101", 55); // line 1 Road r2 = new Road("Elm Street"); // line 2 Highway r3 = new Road("Sullivan Street"); // line 3 Highway r4 = new Highway("New Jersey Turnpike", 65); // line 4 Which of the following best explains the error, if any, in the code segment?

C. Line 3 will cause an error because a Highway variable cannot be instantiated as an object of type Road.

Consider the following class definitions. public class Thing { /* implementation not shown */ } public class MoreThing extends Thing { /* implementation not shown */ } The following code segment appears in a class other than Thing or MoreThing. Thing[] arr = new MoreThing[3]; // line 1 Thing t1 = new Thing(); Thing t2 = new MoreThing(); // line 3 MoreThing t3 = new MoreThing(); arr[0] = t1; // line 5 arr[1] = t2; // line 6 arr[2] = t3; // line 7 Which of the following best explains the error in the code segment?

C. Line 5 will cause an error because the types of arr[0] and t1 are different.

Consider the following class declarations. public class Publication { private String title; public Publication() { title = "Generic"; } public Publication(String t) { title = t; } } public class Book extends Publication { public Book() { super(); } public Book(String t) { super(t); } } The following code segment appears in a method in another class. Book myBook = new Book("Adventure Story"); // Line 1 Book yourBook = new Book(); // Line 2 Which of the following best describes the result of executing the code segment?

C. Object myBook is created using the one-argument Book constructor, which uses super to set myBook's title attribute to "Adventure Story". Object yourBook is created using super to call to the Publication no-argument constructor to set yourBook's title attribute to "Generic".

Consider the following class definitions. public class Drink { // implementation not shown } public class Coffee extends Drink { // There may be instance variables and constructors that are not shown. // No methods are defined for this class. } The following code segment appears in a method in a class other than Drink or Coffee. Coffee myCup = new Coffee(); myCup.setSize("large"); Which of the following must be true so that the code segment will compile without error?

C. The Drink class must have a public method named setSize that takes a String value as its parameter.

Consider the following class definition. public class Pet { private String name; private int age; public Pet(String str, int a) { name = str; age = a; } public getName() { return name; } } Which choice correctly explains why this class definition fails to compile?

C. The accessor method is missing a return type.

Consider the following code segment, which is intended to calculate the average of two quiz scores. double avg = 15 + 20; avg /= 2; Which of the following best describes the behavior of the code segment?

C. The code segment stores 17.5 in avg because 17.5 is the result of the floating point division of 35.0 by 2.

Consider the following code segment, which is intended to display 0.5. int num1 = 5; int num2 = 10; double ans = num1 / num2; System.out.print(ans); Which of the following best describes the error, if any, in the code segment?

C. The code should have cast either num1 or num2 in the expression num1 / num2 to double.

Consider the following search method. public static int search(int[] arr, int target) { int result = -1; for (int j = 0; j < arr.length; j++) { if (arr[j] == target) { result = j; // Line 8 } } return result; } Which of the following describes the effect of replacing the statement in line 8 of the method with result = arr[j]; ?

C. The modified method will return target if target appears in arr and will return -1 otherwise.

Consider the following class definitions. public class Book { private String bookTitle; public Book() { bookTitle = ""; } public Book(String title) { bookTitle = title; } } public class TextBook extends Book { private String subject; public TextBook(String theSubject) { subject = theSubject; } } The following code segment appears in a method in a class other than Book or TextBook. Book b = new TextBook("Psychology"); Which of the following best describes the effect of executing the code segment?

C. There is an implicit call to the zero-parameter Book constructor. The instance variable bookTitle is then initialized to "". Then, the instance variable subject is initialized with the value of the parameter theSubject.

Consider the following method definition. The method isReversed is intended to return true if firstList and secondList contain the same elements but in reverse order, and to return false otherwise. /** Precondition: firstList.size() == secondList.size() */ public static boolean isReversed(ArrayList<Integer> firstList, ArrayList<Integer> secondList) { for (int j = 0; j < firstList.size() / 2; j++) { if (firstList.get(j) != secondList.get(secondList.size() - 1 - j)) { return false; } } return true; } The method does not always work as intended. For which of the following inputs does the method NOT return the correct value?

C. When firstList is {1, 3, 5, 7} and secondList is {5, 5, 3, 1}

Consider the following method. public double secret(int x, double y) { return x / 2.0; } Which of the following lines of code, if located in a method in the same class as secret, will compile without error?

C. double result = secret(4, 4.0);

Consider the following class definition. public class Beverage { private int temperature; public Beverage(int t) { temperature = t; } public int getTemperature() { return temperature; } public boolean equals(Object other) { if (other == null) { return false; } Beverage b = (Beverage) other; return (b.getTemperature() == temperature); } } The following code segment appears in a class other than Beverage. Assume that x and y are properly declared and initialized int variables. Beverage hotChocolate = new Beverage(x); Beverage coffee = new Beverage(y); boolean same = /* missing code */; Which of the following can be used as a replacement for /* missing code */ so that the boolean variable same is set to true if and only if the hotChocolate and coffee objects have the same temperature values?

C. hotChocolate.equals(coffee)

A teacher determines student percentages in a course as the points a student earns divided by the total points available in the grading period. Points are awarded only in whole number increments, but student percentages are to be stored as decimals. The following code segment appears in a program used to compute student percentages. Points that a student earns are stored in pointsEarned, the total points available in the grading period are stored in totalPoints, and the student percentage is stored in percentage. int pointsEarned; /* missing code */ Which of the following is most appropriate to replace /* missing code */ in the program?

C. int totalPoints; double percentage;

Consider the following method, which is intended to return the largest value in the portion of the int array data that begins at the index start and goes to the end of the array. /** Precondition: 0 <= start < data.length */ public int maximum(int[] data, int start) { if (start == data.length - 1) { return data[start]; } /* missing statement */ if (val > data[start]) { return val; } else { return data[start]; } } Which of the following can be used as a replacement for /* missing statement */ so that the maximum method works as intended?

C. int val = maximum(data, start + 1);

Consider the following class definition. public class Person { private String name; /* missing constructor */ } The statement below, which is located in a method in a different class, creates a new Person object with its attribute name initialized to "Washington". Person p = new Person("Washington"); Which of the following can be used to replace /* missing constructor */ so that the object p is correctly created?

C. public Person(String n) { name = n; }

The Employee class will contain a String attribute for an employee's name and a double attribute for the employee's salary. Which of the following is the most appropriate implementation of the class?

C. public class Employee { private String name; private double salary; // constructor and methods not shown }

Consider the following class definition. public class Silly { private int var1; private String var2; public Silly(int v1, String v2) { var1 = v1; var2 = v2; } public boolean equals(Object other) { if (other == null) { return false; } Silly s = (Silly) other; return (var1 == s.var1 && var1 == var2.length() && var2.length() == s.var2.length()); } } The following code segment appears in a class other than Silly. Silly s1 = new Silly(3, "abcd"); Silly s2 = new Silly(3, "abcd"); Silly s3 = new Silly(5, "vwxyz"); Silly s4 = new Silly(5, "aaaaa"); Silly s5 = new Silly(5, "efg"); Which of the following Boolean expressions will evaluate to true ?

C. s3.equals(s4)

Consider the following code segment. boolean a = true; boolean b = true; System.out.print((b || (!a || b)) + " "); System.out.print(((!b || !a) && a) + " "); System.out.println(!(a && b) && b); What output is produced when this code segment is executed?

C. true false false

Consider the following method. public void printSomething (int num, boolean val) { num--; System.out.print(val); System.out.print(num); } Consider the following code segment, which appears in a method in the same class as printSomething. printSomething(1, true); printSomething(2, true); What is printed as a result of executing the code segment?

C. true0true1

The printRightToLeft method is intended to print the elements in the ArrayList words in reverse order. For example, if words contains ["jelly bean", "jukebox", "jewelry"], the method should produce the following output. jewelry jukebox jelly bean The method is shown below. public static void printRightToLeft(ArrayList<String> words) { if (words.size() > 0) { System.out.println(words.get(words.size() - 1)); /* missing code */ } } Which of the following can be used to replace /* missing code */ so that the printRightToLeft method works as intended?

C. words.remove(words.size() - 1); printRightToLeft(words);

In the code segment below, myList is an ArrayList of integers. The code segment is intended to remove all elements with the value 0 from myList. int j = 0; while (j < myList.size()) { if (myList.get(j) == 0) { myList.remove(j); } j++; } The code segment does not always work as intended. For which of the following lists does the code segment NOT produce the correct result?

C. {1, 0, 0, 2}

An efficient algorithm is one that is economical in the use of... (2)

CPU time and memory

Consider the following code segment. System.out.println("W"); System.out.println("X"); System.out.print("Y"); System.out.print("Z"); What is printed as a result of executing the code segment?

D. W X YZ

Consider the following method substringFound, which is intended to return true if a substring, key, is located at a specific index of the string phrase. Otherwise, it should return false. public boolean substringFound(String phrase, String key, int index) { String part = phrase.substring(index, index + key.length()); return part.equals(key); } Which of the following is the best precondition for index so that the method will return the appropriate result in all cases and a runtime error can be avoided?

D. 0 <= index < phrase.length() - key.length()

Consider the following code segment. ArrayList<Integer> myList = new ArrayList(); for (int i = 0; i < 4; i++) { myList.add(i + 1); } for (int i = 0; i < 4; i++) { if (i % 2 == 0) { System.out.print(myList.get(i) + " "); } } What output is produced as a result of executing the code segment?

D. 1 3

Consider the following code segment. double p = 10.6; double n = -0.2; System.out.println((int) (p + 0.5)); System.out.print((int) (n - 0.5)); What is printed as a result of executing the code segment?

D. 11 0

Consider the following code segment. int m = 8; int n = 3; if (m + n > 10) { System.out.print(m + n); } if (m - n > 0) { System.out.print(m - n); } What, if anything, is printed as a result of executing the code segment?

D. 115

Consider the code segment below. int x = 10; int y = 20; System.out.print(y + x / y); What is printed as a result of executing the code segment?

D. 20

In the following code segment, assume that the ArrayList wordList has been initialized to contain the String values ["apple", "banana", "coconut", "lemon", "orange", "pear"]. int count = 0; for (String word : wordList) { if (word.indexOf("a") >= 0) { count++; } } System.out.println(count); What is printed as a result of executing the code segment?

D. 4

Consider the following correct implementation of the insertion sort algorithm. public static void insertionSort(int[] elements) { for (int j = 1; j < elements.length; j++) { int temp = elements[j]; int possibleIndex = j; while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) { elements[possibleIndex] = elements[possibleIndex - 1]; possibleIndex--; // line 10 } elements[possibleIndex] = temp; } } The following declaration and method call appear in a method in the same class as insertionSort. int[] arr = {10, 8, 3, 4}; insertionSort(arr); How many times is the statement possibleIndex--; in line 10 of the method executed as a result of the call to insertionSort ? 0

D. 5

Consider the following classes. public class Base { public Base() { System.out.print("Base" + " "); } } public class Derived extends Base { public Derived() { System.out.print("Derived" + " "); } } Assume that the following statement appears in another class. Derived d1 = new Derived(); What is printed as a result of executing the statement?

D. Base Derived

Consider the following code segment. System.out.println(hello); // Line 1 System.out.print(world); // Line 2 The code segment is intended to produce the following output but does not work as intended. hello world Which of the following changes can be made so that the code segment produces the intended output?

D. Changing print in line 2 to println

Consider the following class declarations. public class Parent { public void first() { System.out.print("P"); second(); } public void second() { System.out.print("Q"); } } public class Child extends Parent { public void first() { super.first(); } public void second() { super.second(); System.out.print("R"); } } public class Grandchild extends Child { public void first() { super.first(); System.out.print("S"); } public void second() { super.second(); System.out.print("T"); } } Which of the following code segments, if located in another class, will produce the output "PQRTS" ?

D. Grandchild d = new Grandchild(); d.first();

Consider the following code segment. System.out.print("Hello!"); System.out.println("How "); System.out.print("are "); System.out.print("you?"); What is printed as a result of executing the code segment?

D. Hello!How are you?

Consider the following method, which returns the lesser of its two parameters. public int min(int first, int second) { /* implementation not shown */ } Assume that each of the following expressions appears in a method in the same class as the method min. Assume also that the int variables p, q, and r have been properly declared and initialized. Which of the following expressions evaluates to the minimum value among p, q, and r? I. min(min(p, q), r) II. min(p, min(q, r)) III. min(min(p, q), p)

D. I and II only

Consider the following declaration for a class that will be used to represent points in the xy-coordinate plane. public class Point { private int x; //x-coordinate of the point private int y; //y-coordinate of the point public Point() { x = 0; y = 0; } public Point(int a, int b) { x = a; y = b; } //Other methods not shown } The following incomplete class declaration is intended to extend the above class so that points can be named. public class NamedPoint extends Point { private String name; // name of point //Constructors go here // Other methods not shown } Consider the following proposed constructors for this class. I. public NamedPoint() { name = ""; } II. public NamedPoint(int d1, int d2, String pointName) { x = d1; y = d2; name = pointName; } III. public NamedPoint(int d1, int d2, String pointName) { super(d1, d2); name = pointName; } Which of these constructors would be legal for the NamedPoint class?

D. I and III only

Consider the following class declarations. public class Person { public void laugh() { System.out.print("Hahaha"); } } public class EvilPerson extends Person { public void laugh() { System.out.print("Mwahahaha"); } } public class Henchman extends EvilPerson { // No methods defined } The following code segment appears in a method in another class. alice.laugh(); Under which of the following conditions will the code segment print "Mwahahaha" ? I. When alice has been declared as type Person II. When alice has been declared as type EvilPerson III. When alice has been declared as type Henchman

D. II and III only

Which of the following arithmetic expressions evaluates to 1 ? I. 2 / 5 % 3 II. 2 / (5 % 3) III. 2 / 5 + 1

D. II and III only

Consider the following class definition, which represents two scores using the instance variables score1 and score2. The method reset is intended to set to 0 any score that is less than threshold. The method does not work as intended. public class TestClass { private int score1; private int score2; public TestClass(int num1, int num2) { score1 = num1; score2 = num2; } public void reset(int threshold) { if (score1 < threshold) // line 14 { score1 = 0; // line 16 } else if (score2 < threshold) // line 18 { score2 = 0; } } } Which of the following changes can be made so that the reset method works as intended?

D. In line 18, change else if to if.

Consider the following method. public static void strChange(String str) { if (str.length() > 0) { strChange(str.substring(1)); System.out.print(str.substring(0, 1)); } } Which of the following best describes the behavior of the method?

D. It prints the characters of str in reverse order.

Consider the following method. /* Precondition: j <= k */ public static void mystery(int j, int k) { System.out.println(j); if (j < k) { mystery(j + 1, k); } } Which of the following best describes the behavior of the mystery method?

D. It prints the integers from j to k, inclusive, in order from least to greatest.

Consider the following code segment. int x = /* initial value not shown */; int y = /* initial value not shown */; int z = x; z /= y; z += 2; Which of the following best describes the behavior of the code segment?

D. It sets z to (x / y) + 2.

a.

public class PictureBook extends Book { private String illustrator; public PictureBook(String t, String a, String i) { super(t,a); illustrator = i; } public void printBookInfo() { super.printBookInfo(); System.out.print(" and illustrated by " + illustrator); } }

Part B: StudentAdvance

public class StudentAdvance extends Advance { public StudentAdvance(int days) { super(days); } public double getPrice() { return super.getPrice()/2; } public String toString() { return super.toString() + " Student ID Required"; } }

What is the format of implementing a subclass?

public class Subclass extends Superclass

Question 2 part A: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. Employees at a store are paid daily wages according to the following rules. Each employee is paid the same fixed amount per day. Each employee is paid an additional amount for each item they sold on that day. Daily Bonus:If the number of items sold that day by an employee is greater than a computed threshold, then the employee also receives a bonus equal to 1010 percent of the employee's daily wages. You will write two methods in the Payroll class below. public class Payroll { private int[] itemsSold; // number of items sold by each employee private double[] wages; // wages to be computed in part (b) /** Returns the bonus threshold as described in part (a). */ public double computeBonusThreshold() { /* To be implemented in part (a) */ } /** Computes employee wages as described in part (b) * and stores them in wages. * The parameter fixedWage represents the fixed amount each employee * is paid per day. * The parameter perItemWage represents the amount each employee * is paid per item sold. */ public void computeWages(double fixedWage, double perItemWage) { /* To be implemented in part (b) */ } // Other instance variables, constructors, and methods not shown. } The bonus threshold is calculated based on the number of items sold by all employees on a given day. The employee with the greatest number of sales and the employee with the least number of sales on that day are ignored in the calculation. The average number of items sold by the remaining employees on that day is computed, and this value is used as the bonus threshold. For a given day, the number of items sold by each employee is stored in the array itemsSold. The example below shows the contents of itemsSold for a day in which there were ten employees. Each array index represents an individual employee. For example, itemsSold[3] represents the number of items sold by employee 3. Based on the information in the table, the bonus threshold is calculated as follows. (48+50+37+62+38+70+55+37+64+60)−37−708=51.75(48+50+37+62+38+70+55+37+64+60)−37−708=51.75 (a) Complete the method computeBonusThreshold below, which is intended to return the bonus threshold based on the contents of the itemsSold array. Assume that itemsSold has been filled appropriately, and that the array contains at least three employees. /** Returns the bonus threshold as described in part (a). */ public double computeBonusThreshold() The computeWages method is intended to calculate the wages for each employee and to assign them to the appropriate element of the array wages. For example, wages[3] should be assigned the wages for employee33. An employee's wages consist of their daily wages plus a possible bonus and are calculated as follows. Each employee's wages are equal to the fixed wage plus the number of items sold times the amount paid per item sold. If the employee sold more items than the bonus threshold, the employee also receives a 1010 percent bonus added to their wages. As described in part (a), computeBonusThreshold() returns 51.75 for the example array below. Suppose that fixedWage is 10.0 and perItemWage is 1.5. Employee 00 did not sell more items than the bonus threshold, so employee 00's wages are equal to 10.0 + 1.5 * 48, which evaluates to 82.0. This value will be assigned to wages[0]. Employee 99 sold more items than the bonus threshold, so employee 99 receives a 1010 percent bonus. Employee 99's wages are equal to (10.0 + 1.5 * 60) * 1.1, or 110.0. This value will be assigned to wages[9]. (b) Write the method computeWages. Assume that itemsSold has been filled appropriately, and there are at least three employees in the array. Assume also that the wages array and the itemsSold array have the same length. Your solution must call computeBonusThreshold appropriately to receive full credit. /** Computes employee wages as described in part (b) * and stores them in wages. * The parameter fixedWage represents the fixed amount each employee * is paid per day. * The parameter perItemWage represents the amount each employee * is paid per item sold. */ public void computeWages(double fixedWage, double perItemWage)

public double computeBonusThreshold() { int total = itemsSold[0]; int min = itemsSold[0]; int max = itemsSold[0]; for(int i = 1; i < itemsSold.length; i++) { total += itemsSold[i]; if(itemsSold[i] < min) { min = itemsSold[i]; } if(itemsSold[i] > max) { max = itemsSold[i]; } } return (total - min - max) / (double) (itemsSold.length - 2); }

2a.

public double computeBonusThreshold() { int total = itemsSold[0]; int min = itemsSold[0]; int max = itemsSold[0]; for(int i = 1; i < itemsSold.length; i++) { total += itemsSold[i]; if(itemsSold[i] < min) { min = itemsSold[i]; } if(itemsSold[i] > max) { max = itemsSold[i]; } } return (total - min - max) / (double)(itemsSold.length-2); }

Write the StudentAnswerSheet method getScore. The parameter passed to method getScore is an ArrayList of strings representing the correct answer key for the test being scored. The method computes and returns a double that represents the score for the student's test answers when compared with the answer key. One point is awarded for each correct answer and ¼ of a point is deducted for each incorrect answer. Omitted answers (indicated by "?") do not change the student's score. Complete method getScore below.

public double getScore(ArrayList<String> key) { double score = 0; for(int i = 0; i < answers.size(); i++) { if(answers.get(i).equals(key.get(i))) { score+=1; } else if(!answers.get(i).equals("?")) { score -= 0.25; } } return score; }

What are the three methods of traversing a 2D array?

row-column, for-each loop, and row-by-row array processing

The _____ of a variable or method is the region in which that variable or method is visible and can be accessed.

scope

block of code

segment of code between a pair of opening and closing curly braces ({ and })

The compiler figures out which method to call by examining a method's...

signature

The java files that comprise your program are called...

source files

All methods defined in the main program must be...

static

All of the functions and constants in the Math class are...

static

The keyword ________ is used for methods that will not access any objects of a class.

static

The compiler selecting the correct overloaded method at compile time is known as...

static binding/early binding

A method that performs an operation for the entire class, not its individual objects, is called a(n)...

static method

A ____ ___________ contains a value that is shared by all instances of the class

static variable

The process of breaking a long method into a sequence of smaller tasks is sometimes known as...

stepwise refinement

char data type

stores single keyboard characters

A subclass can call a method in its superclass by using...

super

What keyword is necessary in order to invoke a method from a superclass?

super

What is within the body of the constructor of a subclass is no constructor is provided?

super();

assignment operator

the = symbol which is used to store a value in a variable

ASCII

the American Standard Code for Information Interchange which defines values for letters, numbers, punctuation marks, and some non-printable functions

When a run-time error occurs, what exactly throws the exception?

the Java run-time environment

polymorphism

the ability of being able to assign a different usage to a method and/or object

Binary search only works if...

the array is sorted

A constructor's name is always the same as...

the class

What does the default toString() return?

the class name, an @, and the memory address of the object

What happens during a compile-time error?

the compiler cannot translate the program into bytecode and prints an error

When a class extends a superclass AND implements an interface, which clause comes first?

the extends clause

floor

the greatest integer less than or equal to the floating point number

What is the worst case for Binary Search?

the key is not in the list or is at the end of a sublist

Define inheritance.

the mechanism by which a new class, called a subclass, is created from an existing class, called a superclass; by absorbing its state and behavior and augmenting these with features unique to the new class.

A method's signature consists of...

the method name and parameter types

When using indexOf, what happens when the parameter string isn't in the string the method is called on?

the method returns a -1

When did object-oriented programming become the dominant programming methodology?

the mid 1990s

In a 2D array, what does arr[i].length represent?

the number of columns

In a 2D array, what does arr.length represent?

the number of rows

If a superclass method calls another method that has been overridden in the subclass, the method that is executed is...

the one in the subclass

flow of control

the order in which statements are executed (sequential, looping, branching, etc.)

What does lexicographical order mean?

the order it comes up in the dictionary

superclass

the parent class of a subclass; a class that has been extended by another class. It allows the class extending it to inherit its state and behaviors.

What does the concatenation operator do with a String and a primitive type?

the primitive type is converted to a String, and the two are combined into one String

inheritance

the process by which a class automatically contains the variables and methods defined in its superclass

What is encapsulation?

the process of bundling a group of methods and data fields into a class

casting

the process of changing the value of one data type into a value of another data type

evaluation

the process of determining the value of an expression

overloading

the process that allows multiple methods to share the same name as long as their parameter lists differ

How does a top-down design work?

the programmer starts with an overview of the program, selects the highest-level controlling object and the tasks needed.

modulus

the remainder after performing division when the % sign is used in an arithmetic expression

In polymorphism, what determines the actual method that will be called?

the run-time environment

.length( );

the total number of characters in a string

Define procedural abstraction.

the use of helper methods within a class

negation

the use of the logical operator ! (not) to reverse the evaluation of a Boolean expression from true to false or from false to true

user interface

the way a user interacts with a computer program

What three characteristics do all container classes share?

they're designed to be memory and run-time efficient, they provide methods for insertion and removal of items, and they provide for iteration over the entire collection

Why should you redefine the toString method for all of your classes?

to help in debugging

What are escape sequences used for?

to print special characters

Why is a ClassCastException thrown?

to signal an attempt to cast an object to a class of which it is not an instance

What is the purpose of a driver class?

to test the class fully before incorporating it as an object in a completely different class

What methods of Object are important to know? (2)

toString; equals

Procedural abstraction is an example of...

top-down development

How do you print the elements of an array?

traverse the array and explicitly print each element

True or false: A class that extends a superclass can also implement an interface.

true

True or false: A subclass may not override static methods of the superclass

true

True or false: constant identifiers are capitalized.

true

True or false: local vars take precedence over instance vars with the same name

true

True or false: subclasses can only access the public methods of their superclasses.

true

An ________ exception is one where you don't provide code to deal with the error.

unchecked

What is program maintenance?

upgrading the code as circumstances change?

What causes a syntax error?

violating the rules of the programming language

What does it mean for primitive types if parameters are passed by value?

when a method is called, a new memory slot is allocated for each parameter

What is infinite recursion?

when a recursive method has no base case

public

when a variable, method, or class is public, it can be seen and used by any other class

What is a logic error?

when the program compiles and runs but the result is wrong

What are the three characteristics of a robust program?

won't give inaccurate answers for input data, won't crash if the input data is invalid, and won't allow execution to proceed if invalid data is entered

merge sort

works by using a divide and conquer method to split the array apart until there are 1 element sets; these sets are then merged back together in sorted order; after all the merges are complete, the array is sorted

Is the following order of operator precedence correct? 1) !, ++, -- 2) *, /, % 3) +, - 4) <, >, <=, >= 5) ==, != 6) && 7) || 8) =, +=, -=, *=, /=, %=

yes

What does a string literal consist of?

zero or more characters, escape sequences, surrounded by double quotes

What logical operator does the following truth table correspond to? ? | T F -------------- T | T T F | T F

||

Consider the following class definitions. public class Appliance { private int id; private String brand; public Appliance(int aId, String aBrand) { /* implementation not shown */ } public String display() { /* implementation not shown */ } } public class Refrigerator extends Appliance { private int numOfDoors; public Refrigerator(int rId, String rBrand, int rNumOfDoors) { /* implementation not shown */ } } The following code segment appears in a class other than Appliance or Refrigerator. public static void displayFeatures(Refrigerator r) { System.out.println(r.display()); // Line 3 } Appliance a1 = new Refrigerator(456, "AllBrand", 2); // Line 6 Refrigerator a2 = new Refrigerator(789, "Xtreme", 3); // Line 7 displayFeatures(a1); // Line 8 displayFeatures(a2); // Line 9 Which of the following best explains why the code segment will not compile?

D. Line 8 causes a compile-time error because the parameter a1 in the call displayFeatures(a1) has the incorrect data type.

Consider the following definition of the class Student. public class Student { private int grade_level; private String name; private double GPA; public Student (int lvl, String nm, double gr) { grade_level = lvl; name = nm; GPA = gr; } } Which of the following object initializations will compile without error?

D. Student max = new Student (10, "Max", 3.75);

Consider the following class definitions. public class Bird { private int beakStrength; public void Bird(int input) { beakStrength = input; } public void setBeakStrength(int strength) { beakStrength = strength; } } public class Hawk extends Bird { private int talonStrength; public Hawk(int talon, int beak) { super(beak); talonStrength = talon; } } The following statement appears in a method in another class. Bird b = new Hawk(5, 8); Which of the following best describes the effect of executing the statement?

D. The Bird variable b is instantiated as a Hawk. The call super(beak) invokes the Bird constructor and initializes the instance variable beakStrength with the value from the parameter beak. The instance variable talonStrength is then initialized with the value from the parameter talon.

Consider the following class. public class Help { private int h; public Help(int newH) { h = newH; } public double getH() { return h; } } The getH method is intended to return the value of the instance variable h. The following code segment shows an example of creating and using a Help object. Help h1 = new Help(5); int x = h1.getH(); System.out.println(x); Which of the following statements best explains why the getH method does not work as intended?

D. The getH method should have a return type of int.

Consider the following class declaration. public class Student { private String name; private int age; public Student(String n, int a) { name = n; age = a; } public boolean isOlderThan5() { if (age > 5) { return true; } } } Which of the following best describes the reason this code segment will not compile?

D. The isOlderThan5 method is missing a return statement for the case when age is less than or equal to 5.

Consider the following class definitions. public class Person { private String firstName; private String lastName; public Person(String pFirstName, String pLastName) { firstName = pFirstName; lastName = pLastName; } public void personInfo() { System.out.println("My name is " + firstName + " " + lastName); } } pubic class Teacher extends Person { private String school; private String subject; public Teacher(String tFN, String tLN, String tSchool, String tSubject) { super(tFN, tLN); school = tSchool; subject = tSubject; } public void teacherInfo() { personInfo(); System.out.println("I teach " + subject + " at " + school); } } The following code segment appears in a class other than Person or Teacher. Person teach = new Teacher("Henry", "Lowe", "PS 150", "English"); teach.teacherInfo(); Which of the following best explains why the code segment will not compile?

D. The variable teach should be declared as a Teacher data type because teacherInfo is a method in the Teacher class.

Consider the following code segment: /* data type 1 */ x = 0.5; /* data type 2 */ y = true; Which of the following best describes the data types that should be used to replace/* data type 1 */ and /* data type 2 */ so that the code segment compiles without error?

D. The variable x should be declared as a double and the variable y should be declared as a boolean.

Consider the following class declaration. public class Thing { private String color; public Thing() { color = "Blue"; } public Thing(String setColor) { color = setColor; } } Which of the following code segments, when appearing in a class other than Thing, would create a reference of type Thing with a value of null ?

D. Thing someThing;

Consider the following class definitions. public class Vehicle { private int numOfWheels; public Vehicle(int nNumOfWheels) { numOfWheels = nNumOfWheels; } public String toString() { return "Number of Wheels: " + numOfWheels; } } public class Motorized extends Vehicle { private int maxSpeed; public Motorized(int nNumOfWheels, nMaxSpeed) { super(nNumOfWheels); maxSpeed = nMaxSpeed; } public String toString() { String s = super.toString() + " Max Speed: "; if (maxSpeed <= 10) { s += "Slow"; } else if (maxSpeed > 10 && maxSpeed <= 100) { s += "Fast"; } else { s += "Super Speedy"; } return s; } } Which of the following code segments, when executed in a class other than Vehicle or Motorized, will display Number of Wheels: 4 Max Speed: Fast ?

D. Vehicle obj = new Motorized(4, 55); System.out.println(obj);

The removeElement method is intended to remove all instances of target from the ArrayList object data passed as a parameter. The method does not work as intended for all inputs. public void removeElement(ArrayList<Integer> data, int target) { for (int j = 0; j < data.size(); j++) { if (data.get(j).equals(target)) { data.remove(j); } } } Assume that the ArrayList object scores and the int variable low_score have been properly declared and initialized. In which of the following cases will the method call removeElement(scores, low_score) fail to produce the intended result?

D. When scores is [8, 8, 4, 3, 3, 6] and low_score is 3

Consider the following code segment. ArrayList<Integer> nums = new ArrayList<>(); nums.add(3); nums.add(2); nums.add(1); nums.add(0); nums.add(0, 4); nums.set(3, 2); nums.remove(3); nums.add(2, 0); Which of the following represents the contents of nums after the code segment has been executed?

D. [4, 3, 0, 2, 0]

Consider the following variable declarations and initializations. int a = 2; int b = 6; int c = 3; Which of the following expressions evaluates to false ?

D. a < b != c < b

Consider the following code segment. int a = 1; int b = 0; int c = -1; if ((b + 1) == a) { b++; c += b; } if (c == a) { a--; b = 4; } What are the values of a, b, and c after this code segment has been executed?

D. a = 1, b = 1, and c = 0

Consider the following code segment, which uses properly declared and initialized int variables x and y and the String variable result. String result = ""; if (x < 5) { if (y > 0) { result += "a"; } else { result += "b"; } } else if (x > 10) { if (y < 0) { result += "c"; } else if (y < 10) { result += "d"; } result += "e"; } result += "f"; What is the value of result after the code segment is executed if x has the value 15 and y has the value 5 ?

D. def

Consider the following code segment, which is intended to set the Boolean variable inRange to true if the integer value num is greater than min value and less than max value. Otherwise inRange is set to false. Assume that inRange, num, min, and max have been properly declared and initialized. boolean isBigger; boolean isSmaller; boolean inRange; if (num < max) { isSmaller = true; } else { isSmaller = false; } if (num > min) { isBigger = true; } else { isBigger = false; } if (isBigger == isSmaller) { inRange = true; } else { inRange = false; } Which of the following values of num, min, and max can be used to show that the code does NOT work as intended?

D. num = 50, min = 50, max = 50

Consider the following two classes. public class Dog { public void act() { System.out.print("run "); eat(); } public void eat() { System.out.print("eat "); } } public class UnderDog extends Dog { public void act() { super.act(); System.out.print("sleep "); } public void eat() { super.eat(); System.out.print("bark "); } } Assume that the following declaration appears in a class other than Dog.Dog fido = new UnderDog ( ) ;What is printed as a result of the call fido.act() ?

D. run eat bark sleep

Consider the following class definitions. public class Book { private String author; private String title; public Book(String the_author, String the_title) { author = the_author; title = the_title; } } public class Textbook extends Book { private String subject; public Textbook(String the_author, String the_title, String the_subject) { /* missing implementation */ } } Which of the following can be used to replace /* missing implementation */ so that the Textbook constructor compiles without error?

D. super(the_author, the_title); subject = the_subject;

Consider the following code segment. int x; int y; x = 3; y = /* missing expression */; x = 1 + 2 * y; System.out.print(x); System.out.println(y); Which of the following can be used as a replacement for /* missing expression */ so that the code segment prints 94 ?

D. x + 1

Consider the following mergeSortHelper method, which is part of an algorithm to recursively sort an array of integers. /** Precondition: (arr.length == 0 or 0 <= from <= to <= arr.length) * arr.length == temp.length */ public static void mergeSortHelper(int[] arr, int from, int to, int[] temp) { if (from < to) { int middle = (from + to) / 2; mergeSortHelper(arr, from, middle, temp); mergeSortHelper(arr, middle + 1, to, temp); merge(arr, from, middle, to, temp); } } The merge method is used to merge two halves of an array (arr[from] through arr[middle], inclusive, and arr[middle + 1] through arr[to], inclusive) when each half has already been sorted into ascending order. For example, consider the array arr1, which contains the values {1, 3, 5, 7, 2, 4, 6, 8}. The lower half of arr1 is sorted in ascending order (elements arr1[0] through arr1[3], or {1, 3, 5, 7}), as is the upper half of arr1 (elements arr1[4] through arr1[7], or {2, 4, 6, 8}). The array will contain the values {1, 2, 3, 4, 5, 6, 7, 8} after the method call merge(arr1, 0, 3, 7, temp). The array temp is a temporary array declared in the calling program. Consider the following code segment, which appears in a method in the same class as mergeSortHelper and merge. int[] vals = {80, 50, 30, 20, 60, 70}; int[] temp = new int[vals.length]; mergeSortHelper(vals, 0, vals.length - 1, temp); Which of the following represents the arrays merged the last time the merge method is executed as a result of the code segment above?

D. {30, 50, 80} and {20, 60, 70} are merged to form {20, 30, 50, 60, 70, 80}.

What are the four steps to Binary Search?

Divide the array in half, check to see if the middle value is the key, search the former half, and search the latter half.

Consider the following code segment in which the int variables a and b have been properly declared and initialized. if (a < b) { a++; } else if (b < a) { b++; } else { a++; b++; } Which of the following code segments is equivalent to the code segment above?

E. if (a == b) { a++; b++; } else if (a < b) { a++; } else { b++; }

Consider the following code segment. int j = 10; int k = 8; j += 2; k += j; System.out.print(j); System.out.print(" "); System.out.println(k); What is printed when the code segment is executed?

E. 12 20

Consider the following code segment. int x = 0; x++; x += 1; x = x + 1; x -= -1; System.out.println(x); What is printed when the code segment has been executed?

E. 4

In the following code segment, assume that the ArrayList numList has been properly declared and initialized to contain the Integer values [1, 2, 2, 3]. The code segment is intended to insert the Integer value val in numList so that numList will remain in ascending order. The code segment does not work as intended in all cases. int index = 0; while (val > numList.get(index)) { index++; } numList.add(index, val); For which of the following values of val will the code segment not work as intended?

E. 4

A school administrator has created a Student class. The class contains variables to represent the following. An int variable called studentID to represent the student's ID number A String variable called studentName to represent the student's name The school administrator has also created a Parent class. The class contains variables to represent the following. A String variable called parentName to represent the parent's name A String variable called email to represent the parent's e-mail address The object penelope will be declared as type Student. The object mrsPatel will be declared as type Parent. Which of the following descriptions is accurate?

E. An attribute of the mrsPatel object is email.

Consider the following statement, which is intended to create an ArrayList named arrList to store elements only of type String. /* missing code */ = new ArrayList<String>(); Which of the following can be used to replace /* missing code */ so that the statement works as intended?

E. ArrayList<String> arrList

Consider the following class definitions. public class Artifact { private String title; private int year; public Artifact(String t, int y) { title = t; year = y; } public void printInfo() { System.out.print(title + " (" + year + ")"); } } public class Artwork extends Artifact { private String artist; public Artwork(String t, int y, String a) { super(t, y); artist = a; } public void printInfo() { /* missing implementation */ } } The following code segment appears in a method in another class. Artwork starry = new Artwork("The Starry Night", 1889, "Van Gogh"); starry.printInfo(); The code segment is intended to produce the following output. The Starry Night (1889) by Van Gogh Which of the following can be used to replace /* missing implementation */ in the printInfo method in the Artwork class so that the code segment produces the intended output?

E. super.printInfo(); System.out.print(" by " + artist);

How does sequential search work?

Each element in an array is compared until the key is found

True or false: A class can only have one interface.

False

True or false: It's impossible for an abstract class to have no abstract methods.

False

Name the two steps of Selection Sorting.

Find the smallest element in the unsorted section of the array, then put that element at the front of the unsorted section.

Linear Search

Given a list and an element to search for, return the index of that element in the list.

What is the best case for insertion sort? Why?

If it's already sorted in increasing order, because it will not need to make any moves.

What is the worst case for insertion sort? Why?

If it's already sorted in reverse order; because it will need the maximum number of moves

How do you read the results of a String compareTo method?

If it's less than 0, the String it's called on comes first in the dictionary. If it's greater than 0, the String it's called on comes after. If it's equal to 0, the two Strings are identical.

When will the equals() method return true?

If the objects being compared reference the same memory slot

A(n) __________ exception is thrown to indicate that a parameter does not satisfy a method's precondition

IllegalArgumentException

What happens when there are too many recursive calls?

It can cause memory overflow

What does it mean if a method is polymorphic?

It has been overridden in at least one subclass

What is the main disadvantage of mergesort?

It uses a temporary array

extends

Keyword used to determine the inheritance of the Superclass and subclass

Part A: Write a statement to create a LightSequence object gradShow that has the initial light sequence "0101 0101 0101". Write the statement below.

LightSequence gradShow = new LightSequence("0101 0101 0101");

The ArrayList class implements what interface?

List

How do you invoke methods in the Math class?

Math, followed by the dot operator

Provide code to find a random real value in the range [2.0,3.0).

Math.random() + 2

Are constructors from superclasses inherited by subclasses?

No

Assuming GradStudent and UnderGrad are subclasses of Student, is the following code legal? GradStudent g = new Student(); Undergrad u = new Student();

No

Will this code cause an error? Why or why not? int x = (GradStudent s).getID();

No, because s is cast to GradStudent before the method is run

An attempt to invoke an instance method with a null reference may throw a...

NullPointerException

HashMap

O (n) A data structure that maps a key to a value or multiple values.

What does the method Math.pow(base, exp) do?

Returns base^exp.

.size( );

Returns the length of an ArrayList

.length;

Returns the length of an array

What sorting method is known as a "search-and-swap" algorithm?

Selection Sort

Why would you use a wrapper class?

Some methods need the parameters to be objects

What error will be thrown if infinite recursion occurs?

StackOverflowError

Part D: Write a code segment that will call the insertSegment method to insert the segment "1111 1111" in the current sequence for gradShow at index 4. The resulting sequence will be stored in the string resultSeq. Write the code segment below.

String resultSeq = gradShow.insertSegment("1111 1111", 4);

_________ is an object in the System class that allows output to be displayed on the screen.

System.out

Part F: Two lights will be arranged on a two-dimensional plane. The vertical distance between the two lights is stored in the double variable a. The horizontal distance between the two lights is stored in the double variable b. The straight-line distance between the two lights is given by the formula . Write a code segment that prints the straight-line distance between the two lights according to the formula above.

System.out.println(Math.sqrt(a*a + b*b));

What happens when an object is passed as a parameter?

The address is copied into local memory, but not the values of the instance variables

Define polymorphism.

The mechanism of selecting the appropriate method of a particular object in a class hierarchy.

What happens when a method actually terminates in a recursive loop?

The program returns to the most recent call

String objects are immutable. What does this mean?

There are no methods to change them after they've been constructed.

Why are String objects unusual? (think about initialization)

They can be initialized like a primitive type

Binary Search

This algorithm ( O (log (n)) finds the position of a specified value, or key, within a sorted array. Eliminates half of the array with each iteration of the loop to find the target quickly.

True or false: A class can have just one superclass.

True

True or false: An abstract class may or may not have constructors.

True

True or false: Math.random() can return a random real number from 0.0 up to (but NOT including) 1.0.

True

True or false: No instance can be created for an abstract class.

True

True or false: Private methods from superclasses cannot be overridden in subclasses.

True

True or false: The efficiency of mergesort is unaffected by the initial sorting of the methods.

True

True or false: When writing a class, constructors and methods should be added and tested one at a time.

True

True or false: you can't have two methods with identical signatures but different return types.

True

Define tail recursion.

When a method has no pending statements after its recursive call

When should you use recursion?

When it significantly simplifies the code

Collision

When two keys have the same value in a HashMap.

Assuming GradStudent and UnderGrad are subclasses of Student, is the following code legal? Student g = new Student(); Student s = new GradStudent(); Student u = new Undergrade();

Yes

When passing an array as a parameter, can you modify it? Why or why not?

Yes, because you're passing its object reference and not a copy

Will this code cause an error? Why or why not? int x = (GradStudent) s.getID();

Yes; dot operator has higher precedence so s.getID() runs before s can be cast to GradStudent

How do you do insertion sort?

You move through the array one element at a time, and sort each element as it comes up.

What is the domain of the result when Math.random() is called?

[0.0,1.0)

What are the three escape sequences necessary to know for the AP exam?

\n, \", \\

During binary search, what happens if the 'key' value isn't in the array?

a -1 is returned

interface

a Java keyword that defines a set of abstract methods to be implemented by a specific class; objects of this type cannot be instantiated.

What are the two parts of a recursive method?

a base case and a non-base case

class hierarchy

a class hierarchy displays classes in a hierarchy; the hierarchy is a specialized form of the class above it

What is a container class?

a class or data structure that holds other objects

What is a driver class?

a class that contains a main method that can be used to test the program as you go

What is an independent class?

a class whose methods don't need any other class to function

data structure

a collection of data that is referred to by one name such as arrays and array lists

Define interface.

a collection of related abstract methods

What kind of error is a syntax error?

a compile-time error

What is the opposite of an abstract class?

a concrete class

array

a data structure containing a single type of data (e.g. ints, Strings, etc.) which is accessed by index positions

What is an array?

a data structure used to implement a list object, where the elements in the list are of the same type

primitive data types

a data type defined by a programming language; e.g. int, double

class

a data-type in object-oriented programming that consists of a group of objects with the same properties and behaviors and that is arranged in a hierarchy with other such data types

class diagram

a diagram that depicts use and inheritance relationships between classes

What can you use to test a class as you go?

a dummy Tester class

Define a stub method.

a dummy method that is called by another method being tested

Define program design.

a fairly detailed plan for solving the problem outlined in the specification

What should you use to traverse elements in an array?

a for loop

nested loop

a loop which appears within the body of another loop

method

a method is a collection of statements that are grouped together to perform an operation and can be invoked at any point in the program by utilizing its name

escape sequence

a pair of symbols beginning with a backslash that has a special meaning within a print statement

pseudocode

a pre-programming technique for representing an algorithm in English-like statements

What is an algorithm?

a precise step-by-step procedure that solves a problem or achieves a goal

double data type

a primitive data type that represents floating point decimal values

int data type

a primitive data type that represents integer values. Ranges from -2147483648 to 2147483648

object-oriented progamming

a program design technique based on modeling the interaction between classes of objects

operating system

a program that manages system-level tasks a computer performs

Interactive Development Environment (IDE)

a programming environment that includes an editor, debugger, and compiler

What kind of error is an infinite loop?

a run-time error

byte

a sequence of 8 bits used to encode a single character

What is a String object defined as?

a sequence of characters

What is test data?

a set of input values to test the program with

algorithm

a set of instructions for a task

bits

a single binary digit (0 or 1)

instance

a specific realization of any object

Unified Modeling Language (UML)

a standard for visually representing the design and documentation of a computer program

conditional

a statement involving a binary decision

What is a postcondition?

a statement of what is true immediately after execution of that code

What is a precondition?

a statement of what is true immediately before execution of that code

constructors

a statement that instantiates an object and initializes the object's private instance variables

Which is bigger: a subclass or a superclass?

a subclass; it contains more data and more methods

operator

a symbol specifying a mathematical or logical operation

variable

a symbol that represents a value and identifies its storage location in memory

What is a base case?

a termination condition that causes the method to end

Define a UML diagram.

a tree-like representation of relationship between classes

What is a matrix?

a two-dimensional array

abstract class

a type of class that is not meant to be instantiated and cannot be instantiated

operand

a value or variable that is operated on in an arithmetic expression

Define a specification.

a written description of the project

What four Math methods are necessary to know for the exam?

abs, pow, sqrt, and random

Abstract methods are declared with the keyword...

abstract

An abstract class may contain...

abstract methods

Give the formula for a method header.

access specifier, return type, method name, parameter list

A(n) _______ method accesses a class object without altering the object

accessor

Getter methods are also known as...

accessor methods

How does the compareTo method compare Strings?

according to their position in the ASCII chart, or lexicographical order

What is a nonbase case?

actions that move the algorithm towards termination

Method calls are always determined by the type of the ________ _______, not the type of the object reference.

actual object

The parameters one uses when actually using a method are known as _______ parameters or __________.

actual, arguments

What five methods of List<E> are important to know?

add, size, get, set, and remove

Having two references for the same object is known as...

aliasing

What should a proper program design include?

all objects that will be used, the data structures that will implement them, and a detailed list of tasks the program will perform

What happens when you use a negative number when calling the String substring method?

an IndexOutOfBoundsException

precondition

an assertion that should be true at the moment when the method is called

postcondition

an assertion that should be true when the method completes execution

object

an instance of a class; has a state and a behavior

concatenation

an operation which combines two strings into one

logical operators

an operator that can be applied to boolean values or expressions ( && , || )

relational operators

an operator used to compare two values, variables, or expressions

Name the 5 steps of the waterfall model.

analysis of the specification, program design, implementation, testing & debugging, and maintenance

What is the first step in writing a program?

analyze the specification, make sure you understand it, and clarify with the customer if anything is unclear.

How can a subclass override a method from its superclass?

by defining a method with the same return type and signature

How can a subclass constructor implement its instance variables exactly the same way as the superclass constructor?

by using the super() method

A compiler converts source code into a machine readable form, called...

bytecode

A(n) ______ is a software blueprint for implementing objects of a given type

class

All Java methods must be contained in a(n)...

class

What does it mean when a class is a collaborator?

classes needed to implement a method

What does the concatenation operator do to two Strings?

combines them into a single String

Assigning a double to an int will cause a(n)...

compile-time error

A __________ converts source code into a machine readable form.

compiler

Operators such as +=, =, -=, and /= are known as __________ operators.

compound assignment

A(n) _______ creates an objects of the class.

constructor

_______ __________ are the mechanism by which you make the statements of a program run in non-sequential order.

control structures

If String objects are immutable, then how do you mutate them?

create a new String

The current state of a given object is maintained in its ____ ______ or _______ _________.

data fields; instance variables

After encapsulation, what is the next step of designing a program?

decide what data fields each class needs and what data structures should store them

base-10 representation

decimal -- (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

if, if-else, nested if, and extended if statements are all known as ______-______ control structures.

decision-making

data type declaration

declares the data type of a variable; e.g. int a;

Define information hiding.

declaring instance variables and helper methods as private so client classes can't use them

A(n) _________ constructor has no arguments.

default

subclass

derived from a superclass; it inherits the public methods and variables from the class it extends

Identifiers may not begin with a(n)...

digit

How are characters sorted in the ASCII chart? (out of capitals, lowercase, and digits, in what order do they come?)

digits, capitals, and lowercases

Java API

documentation for all of Java's classes (API = Application Programming Interface)

Casting a superclass to a subclass type is called a...

downcast

The parameters used in a method heading are known as _____ or ________ parameters.

dummy, formal

When does a compile-time error occur?

during compilation of the program

When does a run-time error occur?

during the execution of the program

Making a run-time decision about which instance method to call is known as...

dynamic binding/late binding

Combining an object's data and methods into a class is known as...

encapsulation

What do you use to test objects for equality?

equals()

A(n) _________ __________ is a backslash followed by a single character.

escape sequence

A(n) __________ is an error condition that occurs during the execution of a Java program.

exception

What does it mean when an exception is thrown?

execution stops and an error message is printed

In the method obj.doSomething(x); "obj" is a(n) ______ parameter and "x" is a(n) ________ parameter.

explicit, implicit

True or False: a subclass cannot redefine a method that it inherits.

false

True or false: A recursive algorithm cannot have more than one base case.

false

True or false: A subclass may redefine a public method as private.

false

True or false: subclasses inherit the private instance variables and private methods of their superclasses.

false

True or false: when chain assignments like the following are used: x = y = z = 0; the statement is evaluated from left to right.

false

What will be the output of the following statement? System.out.println( 5 + 3 < 6 - 1 );

false

When an array with boolean values is declared, what are the values automatically initialize to?

false

A(n) ________ variable is used to name a quantity whose value will not change.

final

When designing a program, how do you identify behaviors?

find useful verbs in the program specification

Once an array has been created, its size is...

fixed

Avoid using boolean operators to compare ______-______ numbers.

floating-point

base-16 representation

hexadecimal -- (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f); begins with 0x

A(n) ____ is a name for a variable, parameter, constant, user-defined method, or user-defined class

identifier

What are the five steps in object-oriented program design?

identify classes to be written, identify behaviors, determine relationships between classes, write the interface for each class, and implement the methods.

What is the worst case in sequential search?

if every element needs to be compared

What is the best case for Binary Search?

if the key is right in the middle

What is the best case in sequential search?

if the key is the first element

Part E: Assume that the string oldSeq has been properly declared and initialized and contains the string segment. Write a code segment that will remove the first occurrence of segment from oldSeq and store it in the string newSeq. Consider the following examples. If oldSeq is "1100000111" and segment is "11", then "00000111" should be stored in newSeq. If oldSeq is "0000011" and segment is "11", then "00000" should be stored in newSeq. If oldSeq is "1100000111" and segment is "00", then "11000111" should be stored in newSeq. Write the code segment below. Your code segment should meet all specifications and conform to the examples.

int index = oldSeq.indexOf(segment); String newSeq = oldSeq.substring(0, index) + oldSeq.substring(index + segment.length());

What primitive types are included in the AP Java subset? (4)

int, boolean, double, char

What is another way to say logic error?

intent error

An interface is declared with the _________ keyword.

interface

An (interface/abstract class) typically does NOT provide implementations for any of its methods, while an (interface/abstract class) can.

interface; abstract class

The relationship that a subclass has to its superclass is informally referred to as a(n)...

is-a relationship

What is an inheritance relationship?

is-a; involves subclasses and superclasses

What does the method boolean add(E obj) do?

it appends obj to the end of the list, and always returns true

What does ArrayList() do?

it constructs an empty list

What happens when you "wrap" a primitive?

it constructs an object from a single value

What does the Math class do?

it implements standard mathematical functions

What does void add(int index, E element) do?

it inserts element at the specified index

What purpose does using constants serve?

it makes it easier to revise the code

If a subclass of an abstract class does not provide implementation code for all the abstract methods of its superclass...

it must also be declared as an abstract class

If a class does not implement all the methods in an interface, what must happen?

it must be declared abstract

What does E remove(int index) do?

it removes and returns the element at the specified index

What does E set(int index, E element) do?

it replaces the item at index with the specified element

What happens when you "unwrap" an object?

it retrieves the primitive value

What does the method Math.abs(x) do?

it returns the absolute value of x

What does indexOf do?

it returns the index of the first occurrence of the parameter String within the String it's called on

What does int length() do?

it returns the length of the String

What does int size() do?

it returns the number of elements in the list

What does a wrapper class do?

it takes either an existing object or a value of primitive type, "wraps" it in an object, and provides new methods for that type.

Why shouldn't you use == to test Strings?

it tests whether they're the same reference, not if they're the same string

When you call the equals method in the Integer class, what happens if the object you use isn't an Integer?

it throws a ClassCastException

What does the Double class do?

it wraps a value of type double in an object

traversal

iteration through an array or ArrayList

In what case will selection and insertion sort be inefficient?

large arrays

An identifier may use... (3)

letters, digits, and underscores

In an ArrayList, the last slot is always...

list.size()-1

A(n) ______ variable is defined inside a method.

local

_________ operators are applied to boolean expressions to form compound boolean expressions.

logical

The ________ method must always be static.

main

What sorting method is known as a "divide-and-conquer" approach?

mergesort

All program statements must be placed inside a(n)...

method

Abstract methods have no...

method body

The ________ of the class provide behaviors exhibited by an object and the operations that manipulate the object

methods

accessors

methods that access private instance variables but do not change them

Define helper methods.

methods that break up larger methods into smaller tasks

mutators

methods that change (or mutates) the values of private instance variables

setters

methods that only assign values to variables or objects

getters

methods that return a value to an invoking statement

A(n) ________ method changes the state of an object by modifying at least one of its instance variables.

mutator

Setter methods are also known as...

mutator methods

In selection/insertion sort, for an array of n elements, the array is sorted after how many passes?

n-1

arithmetic demotion

narrowing conversion; e.g. int x = (int)3.14; truncation

In Java, an array is an object, therefore what keyword is needed when initializing?

new

Do Array objects have a toString method?

no

When you get an overflow error, does Java give you a warning?

no

When getting the length of an array, do you use parentheses? Why or why not?

no, because it's not a method

When an array with object references is declared, what are the elements automatically initialized to?

null

An uninitialized object variable is called a...

null reference/null pointer

A(n) ________ is a single instance of a class.

object

AP CS A concerns _______-__________ programming.

object-oriented

arithmetic promotion

occurs automatically in an expression of mixed types; e.g. double x = 3.14 * 10 * 10; (10s become 10.0s)

underflow condition

occurs when a calculation whose exact result is a number of smaller absolute value than is acceptable

overflow condition

occurs when a calculation whose exact result lies outside of the Java integer range

assignment conversion

occurs when a value with less precision is assigned to a variable with greater precision; widening conversion (narrowing conversion is not possible w/ this method) e.g. double x = 100;

base-8 representation

octal -- (0, 1, 2, 3, 4, 5, 6, 7)

String literal

one or more characters enclosed in double quotation marks

If you try to store a value that is too big in an int variable, you'll get a(n)....

overflow error

________ methods are two or more methods in the same class that have the same name but different parameter lists.

overloaded

Having more that one constructor in the same class is an example of...

overloading

If you want the equals() method to test the contents of an object rather than its memory location, you must...

override the method

Related classes in java are grouped into...

packages

____________ are passed by value

parameters

If part of the original method from the superclass is retained, we refer to the subclass's rewrite as...

partial overriding

When designing a program, how do you identify class names?

pick out "big-picture" nouns from the program specification

Relational operators should generally only be used when comparing...

primitive types

In Java, both ___________ _________ and _______ __________ are passed by value.

primitive types; object references

The ________ method outputs an item without going to a new line afterward.

print

The ______ method outputs an item and then goes to a new line.

println

The keyword ____ signals data or methods are not usable outside the class.

private

loop

program statements that cause a segment of code to be repeated until a terminating condition is met

In the AP Java subset, all classes are...

public

The keyword _____ signals that the class or method is usable outside the class.

public

a.

public class Animal { private String classification; private String species; private String name; public Animal(String c, String s, String n) { classification = c; species = s; name = n; } public String toString() { String str = ""; str = name + " the " + species + " is a " + classification; return str; } }

c.

public class BookListing { private Book myBook; private double cost; public BookListing(Book b, double c) { myBook = b; cost = c; } public void printDescription() { myBook.printBookInfo(); System.out.print(", $" + cost); } }

Part A: class Cat

public class Cat extends Pet { public Cat (String name) { super(name); } public String speak() { return "meow"; } }

c.

public class Elephant extends Herbivore { private double tuskLength; public Elephant(String n, double t) { super("elephant", n); tuskLength = t; } public String toString() { return super.toString() + " with tusks " + tuskLength + " meters long"; } }

b.

public class Herbivore extends Animal { public Herbivore(String s, String n) { super("herbivore", s, n); } }

Part B: class loudDog

public class LoudDog extends Dog { public LoudDog(String name) { super(name); } public String speak() { return super.speak() + super.speak(); }

If several methods in a class require the same task, you should use...

helper methods

When implementing classes, what are the two different kinds of development?

bottom-up and top-down

What is another word for wrapping?

boxing

What is a composition relationship?

has-a; involves wrapper classes

An abstract method only has a...

header

A store sells rope only in whole-foot increments. Given three lengths of rope, in feet, the following code segment is intended to display the minimum length of rope, in feet, that must be purchased so that the rope is long enough to be cut into the three lengths. For example, for lengths of 2.8 feet, 3 feet, and 5 feet, the minimum length of rope that must be purchased is 11 feet. For these inputs, the code segment should display 11. As another example, for lengths of 1.1 feet, 3.2 feet, and 2 feet, the minimum length of rope that must be purchased is 7 feet. For these inputs, the code segment should display 7. double len1; double len2; double len3; double total = len1 + len2 + len3; int minLength = (int) (total + 0.5); System.out.print(minLength); Which of the following best describes the behavior of the code segment?

B. The code segment works as intended but only when the sum of the three lengths is an integer or the decimal part of the sum of the three lengths is greater than or equal to 0.5.

Consider the method sequentialSearch, which takes an ArrayList of Integer elements and an int value as parameters and returns the index of the first appearance of the target value in the list or -1 if the target value does not appear in the list. public static int sequentialSearch(ArrayList<Integer> elements, int target) { for (int j = 0; j < elements.size(); j++) // Line 3 { if (elements.get(j) == target) { return j; } } return -1; } Which of the following explains how replacing Line 3 with for (int j = (elements.size() - 1); j >= 0; j--) will affect the behavior of sequentialSearch?

B. The modified method will return the index of the last appearance of the target value in the list, or -1 if the target value does not appear in the list.

Consider the following class definitions. public class Aclass { public void methodX() { System.out.print("Super X "); methodY(); } public void methodY() { System.out.print("Super Y "); methodZ(); } public void methodZ() ( System.out.print("Super Z"); } } public class Bclass extends Aclass { public void methodX() { super.methodX(); } public void methodY() { System.out.print("Sub Y "); methodZ(); } } The following code segment appears in a class other than Aclass or Bclass. Aclass thing = new Bclass(); thing.methodX(); The code segment is intended to display the following. Super X Super Y Super Z Which of the following best explains why the code segment does not work as intended?

B. The variable thing should be instantiated as an Aclass object because methodY is overridden in Bclass.

Consider the following code segment. ArrayList<String> syllables = new ArrayList<String>(); syllables.add("LA"); syllables.add(0, "DI"); syllables.set(1, "TU"); syllables.add("DA"); syllables.add(2, syllables.get(0)); syllables.remove(1); System.out.println(syllables.toString()); What is printed as a result of executing the code segment?

B. [DI, DI, DA]

Consider the following code segment. ArrayList<String> words = new ArrayList<String>(); words.add("mat"); words.add("new"); words.add("open"); words.add("pet"); int i = 0; while (i < words.size()) { words.remove(i); i++; } System.out.println(words.toString()); What is printed when the code segment is executed?

B. [new, pet]

Consider the following class definition. public class Backyard { private int length; private int width; public Backyard(int l, int w) { length = l; width = w; } public int getLength() { return length; } public int getWidth() { return width; } public boolean equals(Object other) { if (other == null) { return false; } Backyard b = (Backyard) object; return (length == b.getLength() && width == b.getWidth()); } } The following code segment appears in a class other than Backyard. It is intended to print true if b1 and b2 have the same lengths and widths, and to print false otherwise. Assume that x, y, j, and k are properly declared and initialized variables of type int. Backyard b1 = new Backyard(x, y); Backyard b2 = new Backyard(j, k); System.out.println( /* missing code */ ); Which of the following can be used as a replacement for /* missing code */ so the code segment works as intended?

B. b1.equals(b2)

The bark method below is intended to print the string "woof" a total of num times. public static void bark(int num) { if (num > 0) { System.out.println("woof"); /* missing code */ } } Which of the following can be used to replace /* missing code */ so that the call bark(5) will cause "woof" to be printed five times?

B. bark(num - 1);

Consider the following code segment. System.out.print("cat "); System.out.println("dog "); System.out.println("horse "); System.out.print("cow "); What is printed as a result of executing the code segment?

B. cat dog horse cow

Which statement correctly declares a variable that can store a temperature rounded to the nearest tenth of a degree?

B. double patientTemp;

Consider the following statement, which is intended to create an ArrayList named a to store only elements of type Thing. Assume that the Thing class has been properly defined and includes a no-parameter constructor. ArrayList<Thing> a = /* missing code */; Which of the following can be used to replace /* missing code */ so that the statement works as intended?

B. new ArrayList<Thing>()

The Thing class below will contain a String attribute, a constructor, and the helper method, which will be kept internal to the class. public class Thing { /* missing code */ } Which of the following replacements for /* missing code */ is the most appropriate implementation of the class?

B. private String str; public Thing(String s) { /* implementation not shown */ } private void helper() { /* implementation not shown */ }

The Fraction class below will contain two int attributes for the numerator and denominator of a fraction. The class will also contain a method fractionToDecimal that can be accessed from outside the class. public class Fraction { /* missing code */ // constructor and other methods not shown } Which of the following replacements for /* missing code */ is the most appropriate implementation of the class?

B. private int numerator; private int denominator; public double fractionToDecimal() { return (double) numerator / denominator; }

Consider the following code segment. boolean a = true; boolean b = false; System.out.print((a == !b) != false); What is printed as a result of executing this code segment?

B. true

Consider the following code segment. String myString = new String("my string"); String yourString = new String(); yourString = "my string"; boolean dotEquals = myString.equals(yourString); boolean equalsEquals = (myString == yourString); System.out.print(dotEquals + " " + equalsEquals); What is printed as a result of executing the code segment?

B. true false

Consider the following mergeSortHelper method, which is part of an algorithm to recursively sort an array of integers. /** Precondition: (arr.length == 0 or 0 <= from <= to <= arr.length) * arr.length == temp.length */ public static void mergeSortHelper(int[] arr, int from, int to, int[] temp) { if (from < to) { int middle = (from + to) / 2; mergeSortHelper(arr, from, middle, temp); mergeSortHelper(arr, middle + 1, to, temp); merge(arr, from, middle, to, temp); } } The merge method is used to merge two halves of an array (arr[from] through arr[middle], inclusive, and arr[middle + 1] through arr[to], inclusive) when each half has already been sorted into ascending order. For example, consider the array arr1, which contains the values {1, 3, 5, 7, 2, 4, 6, 8}. The lower half of arr1 is sorted in ascending order (elements arr1[0] through arr1[3], or {1, 3, 5, 7}), as is the upper half of arr1 (elements arr1[4] through arr1[7], or {2, 4, 6, 8}). The array will contain the values {1, 2, 3, 4, 5, 6, 7, 8} after the method call merge(arr1, 0, 3, 7, temp). The array temp is a temporary array declared in the calling program. Consider the following code segment, which appears in a method in the same class as mergeSortHelper and merge. int[] numbers = {40, 10, 20, 30}; int[] temp = new int[numbers.length]; mergeSortHelper(numbers, 0, numbers.length - 1, temp); How many times will the merge method be called as a result of executing the code segment?

C. 3

Consider the following code segment. double a = 7; int b = (int) (a / 2); double c = (double) b / 2; System.out.print(b); System.out.print(" "); System.out.print(c); What is printed as a result of executing the code segment?

C. 3 1.5

In the code segment below, assume that the ArrayList object numbers has been properly declared and initialized to contain [0, 2, 4, 5]. for (int k = numbers.size() - 1; k >= 0; k--) { if (numbers.get(k) > k) { System.out.print(k + " "); } } What, if anything, is printed as a result of executing the code segment?

C. 3 2 1

Consider the following code segment. int a = 1; int b = 2; int c = 3; int d = 4; double x = a + b * c % d; What is the value of x when the code segment has been executed?

C. 3.0

Consider the following code segment. int num = 5; num *= 2; num %= 6; What is the value of num after the code segment is executed?

C. 4

Consider the following method, which implements a recursive binary search. /** Returns an index in arr where the value x appears if x appears * in arr between arr[left] and arr[right], inclusive; * otherwise returns -1. * Precondition: arr is sorted in ascending order. * left >= 0, right < arr.length, arr.length > 0 */ public static int bSearch(int[] arr, int left, int right, int x) { if (right >= left) { int mid = (left + right) / 2; if (arr[mid] == x) { return mid; } else if (arr[mid] > x) { return bSearch(arr, left, mid - 1, x); } else { return bSearch(arr, mid + 1, right, x); } } return -1; } The following statement appears in a method in the same class as bSearch. Assume that nums is a sorted array of length 7, containing only positive integers. int result = bSearch(nums, 0, nums.length - 1, -100); How many times will the bSearch method be called as a result of executing the statement, including the initial call?

C. 4

Consider the following correct implementation of the insertion sort algorithm. public static void insertionSort(int[] elements) { for (int j = 1; j < elements.length; j++) { int temp = elements[j]; int possibleIndex = j; while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) { elements[possibleIndex] = elements[possibleIndex - 1]; possibleIndex--; } elements[possibleIndex] = temp; // line 12 } } The following declaration and method call appear in a method in the same class as insertionSort. int[] nums = {8, 7, 5, 4, 2, 1}; insertionSort(nums); How many times is the statement elements[possibleIndex] = temp; in line 12 of the method executed as a result of the call to insertionSort ?

C. 5

Consider the following methods, which appear in the same class. public void methodA(int arg) { int num = arg * 10; methodB(num); } public void methodB(int arg) { System.out.print(arg + 10); } Consider the call methodA(4), which appears in a method in the same class. What, if anything, is printed as a result of the call methodA(4) ?

C. 50

Consider the following method, which implements a recursive binary search. /** Returns an index in myList where target appears, * if target appears in myList between the elements at indices * low and high, inclusive; otherwise returns -1. * Precondition: myList is sorted in ascending order. * low >= 0, high < myList.size(), myList.size() > 0 */ public static int binarySearch(ArrayList<Integer> myList, int low, int high, int target) { int mid = (high + low) / 2; if (target < myList.get(mid)) { return binarySearch(myList, low, mid - 1, target); } else if (target > myList.get(mid)) { return binarySearch(myList, mid + 1, high, target); } else if (myList.get(mid).equals(target)) { return mid; } return -1; } Assume that inputList is an ArrayList of Integer objects that contains the following values. [0, 10, 30, 40, 50, 70, 70, 70, 70] What value will be returned by the call binarySearch(inputList, 0, 8, 70) ?

C. 6

Consider the following code segment. int quant = 20; int unitPrice = 4; int ship = 8; int total; if (quant > 10) { unitPrice = 3; } if (quant > 20) { ship = 0; } total = quant * unitPrice + ship; What is the value of total after this code segment has been executed?

C. 68

The following code segment prints one or more characters based on the values of boolean variables b1 and b2. Assume that b1 and b2 have been properly declared and initialized. if (!b1 || b2) { System.out.print("A"); } else { System.out.print("B"); } if (!(b1 || b2)) { System.out.print("C"); } else { System.out.print("D"); } if (b1 && !b1) { System.out.print("E"); } If b1 and b2 are both initialized to true, what is printed when the code segment has finished executing?

C. AD

A student has created a Book class. The class contains variables to represent the following. An int variable called pages to represent the number of pages A boolean variable called isHardcover to indicate whether or not the book is hardcover The object story will be declared as type Book. Which of the following descriptions is accurate?

C. An attribute of the story object is isHardcover.

Consider the following class definition. public class AnimalPrinter { public void printDog() { System.out.println("dog"); } public void printCat() { System.out.println("cat"); } /* constructors not shown */ } The method myMethod appears in a class other than AnimalPrinter. The method is intended to produce the following output. dog cat Assume that an AnimalPrinter object myPrinter has been properly declared and initialized inside myMethod. Which of the following code segments, if located in myMethod, will produce the intended output?

E. myPrinter.printDog();myPrinter.printCat();

Consider the following class definitions. 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. Computer myPhone = new SmartPhone(2.55, 4.53); System.out.println("Device has memory: " + myPhone.getMemory() + ", screen area: " + myPhone.getScreenWidth() * myPhone.getScreenHeight() + " square inches."); 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?

C. An error occurs during compilation because the getScreenWidth and getScreenHeight methods are not defined for the Computer object myPhone.

Consider the following code segment. String first = new String("duck"); String second = new String("duck"); String third = new String("goose"); if (first == second) { System.out.print("A"); } else if (second == third) { System.out.print("B"); } else if (first.equals(second)) { System.out.print("C"); } else if (second.equals(third)) { System.out.print("D"); } else { System.out.print("E"); } What is printed as a result of executing the code segment?

C. C

Consider the following class declarations. public class Range { private int lowValue; public Range(int low) { lowValue = low; } public String toString() { return "This range starts with " + lowValue; } } public class ClosedRange extends Range { private int highValue; public ClosedRange(int low, int high) { super(low); highValue = high; } public String toString() { return super.toString() + " and ends with " + highValue; } } A code segment appearing in a method in another class is intended to produce the following output. This range starts with 1 and ends with 10 Which of the following code segments will produce this output?

C. ClosedRange r3 = new ClosedRange(1, 10); System.out.println(r3);

Consider the following Vbox class. public class Vbox { private int width; private int height; private int depth; public Vbox(int w, int h, int d) { width = w; height = h; depth = d; } public Vbox(int len) { width = len; height = len; depth = len; } } Which of the following declarations, appearing in a method in a class other than Vbox, will correctly instantiate a Vbox object? I. Vbox b1 = new Vbox(4); II. Vbox b2 = new Vbox(2, 8, 4); III. Vbox b3 = new Vbox(4.0, 4.0, 4.0);

C. I and II only

Consider the following class declarations. public class A { private int x; public A() { x = 0; } public A(int y) { x = y; } // There may be instance variables, constructors, and methods that are not shown. } public class B extends A { private int y; public B() { /* missing code */ } // There may be instance variables, constructors, and methods that are not shown. } Which of the following can be used to replace /* missing code */ so that the statement B temp = new B(); will construct an object of type B and initialize both x and y with 0 ? y = 0 super (0); y = 0; x = 0; y = 0;

C. I and II only

Consider the following class definition. Each object of the class Employee will store the employee's name as name, the number of weekly hours worked as wk_hours, and hourly rate of pay as pay_rate. public class Employee { private String name; private int wk_hours; private double pay_rate; public Employee(String nm, int hrs, double rt) { name = nm; wk_hours = hrs; pay_rate = rt; } public Employee(String nm, double rt) { name = nm; wk_hours = 20; pay_rate = rt; } } Which of the following code segments, found in a class other than Employee, could be used to correctly create an Employee object representing an employee who worked for 20 hours at a rate of $18.50 per hour? I. Employee e1 = new Employee("Lili", 20, 18.5); II. Employee e2 = new Employee("Steve", 18.5); III. Employee e3 = new Employee("Carol", 20);

C. I and II only

Consider the following class definitions. public class Apple { public void printColor() { System.out.print("Red"); } } public class GrannySmith extends Apple { public void printColor() { System.out.print("Green"); } } public class Jonagold extends Apple { // no methods defined } The following statement appears in a method in another class. someApple.printColor(); Under which of the following conditions will the statement print "Red" ? I. When someApple is an object of type Apple II. When someApple is an object of type GrannySmith III. When someApple is an object of type Jonagold

C. I and III only

Consider the following statement, which is intended to create an ArrayList named numbers that can be used to store Integer values. ArrayList<Integer> numbers = /* missing code */; Which of the following can be used to replace /* missing code */ so that the statement works as intended? new ArrayList() new ArrayList<Integer> new ArrayList<Integer>()

C. I and III only

Consider the following method. public static int mystery(ArrayList<Integer> numList) { if (numList.size() == 0) { return 0; } else { int val = numList.remove(0); return val + mystery(numList); } } Which of the following best describes the value returned by the method?

C. It returns the sum of the elements in numList.

Consider the following method findValue, which takes an ArrayList of String elements and a String value as parameters and returns true if the String value is found in the list and false otherwise. public static boolean findValue(ArrayList<String> arr, String key) { for (int j = 0; j < arr.size(); j++) // Line 3 { if (arr.get(j).equals(key)) { return true; } } return false; } Which of the following best explains the impact to the findValue method when, in line 3, int j = 0 is replaced by int j = 1 ?

C. It will cause the method to return a different result when the key value is found only at the first index in the list.

Consider the following class definition. The method appendIt is intended to take the string passed as a parameter and append it to the instance variable str. For example, if str contains "week", the call appendIt("end") should set str to "weekend". The method does not work as intended. public Class StringThing { private String str; public StringThing(String myStr) { str = myStr; } public void appendIt(String s) // line 10 { str + s; // line 12 } } Which of the following changes should be made so that the appendIt method works as intended?

C. Line 12 should be changed to str = str + s;

What SEARCH method is known as a divide-and-conquer approach?

binary

base-2 representation

binary -- (0, 1)

Consider the following two code segments, which are both intended to determine the longest of the three strings "pea", "pear", and "pearl" that occur in String str. For example, if str has the value "the pear in the bowl", the code segments should both print "pear" and if str has the value "the pea and the pearl", the code segments should both print "pearl". Assume that str contains at least one instance of "pea". I. if (str.indexOf("pea") >= 0) { System.out.println("pea"); } else if (str.indexOf("pear") >= 0) { System.out.println("pear"); } else if (str.indexOf("pearl") >= 0) { System.out.println("pearl"); } II. if (str.indexOf("pearl") >= 0) { System.out.println("pearl"); } else if (str.indexOf("pear") >= 0) { System.out.println("pear"); } else if (str.indexOf("pea") >= 0) { System.out.println("pea"); } Which of the following best describes the output produced by code segment I and code segment II?

E. Code segment II produces correct output for all values of str, but code segment I produces correct output only for values of str that contain "pea" but not "pear".

Consider the following class definitions. public class Pet { public void speak() { System.out.print("pet sound"); } } public class Dog extends Pet { public void bark() { System.out.print("woof woof"); } public void speak() { bark(); } } public class Cat extends Pet { public void speak() { System.out.print("meow meow"); } } The following statement appears in a method in another class. myPet.speak(); Under which of the following conditions will the statement compile and run without error? I. When myPet is an object of type Pet II. When myPet is an object of type Dog III. When myPet is an object of type Cat

E. I, II, and III

Consider the following classes. public class Bird { public void sing() { System.out.println("Cheep"); } } public class Duck extends Bird { public void sing() { System.out.println("Quack"); } } public class Chicken extends Bird { // No methods defined } public class Rooster extends Chicken { public void sing() { System.out.println("Cockadoodle doo"); } } The following statement appears in a method in another class. someBird.sing(); Under which of the following conditions will the statement compile and run without error? I. When someBird has been declared as type Duck II. When someBird has been declared as type Chicken III. When someBird has been declared as type Rooster

E. I, II, and III

The volume of a cylinder is equal to the height times the area of the circular base. The area of the circular base is equal to π (pi) times the square of the radius. The code segment below is intended to compute and print the volume of a cylinder with radius r and height h. Assume that the double variables r, h, and pi have been properly declared and initialized. /* missing code */ System.out.print(volume); Which of the following can be used to replace /* missing code */ so that the code segment works as intended? I. double baseArea = pi * r * r;double volume = baseArea * h; II. double volume = pi * r * r;volume = volume * h; III. double volume = pi * r * r * h;

E. I, II, and III

Consider the following class declarations. public class MultiTool { private int blade; private int screwdriver; public MultiTool(int b, int s) { blade = b; screwdriver = s; } } public class DeluxeMultiTool extends MultiTool { private boolean compass; public DeluxeMultiTool(int b, int s, boolean c) { super(b, s); compass = c; } public String getCompass() { return compass + ""; } } The following code segment appears in a method in another class. ArrayList<MultiTool> toolList = new ArrayList<MultiTool>(); MultiTool tool1 = new DeluxeMultiTool(4, 2, false); // Line 2 DeluxeMultiTool tool2 = new DeluxeMultiTool(3, 1, true); // Line 3 toolList.add(tool1); // Line 4 toolList.add(tool2); // Line 5 for (MultiTool tool : toolList) { System.out.println(tool.getCompass()); // Line 8 } The code segment does not compile. Which of the following best explains the cause of the error?

E. Line 8 causes a compile-time error because the getCompass method is not defined for objects of type MultiTool.

Consider the method seqSearch, which implements a sequential search algorithm. public int seqSearch(int[] arr, int target) { for (int j = 0; j < arr.length; j++) { if (arr[j] == target) { return j; } } return -1; } Consider another method, seqSearch2, which modifies seqSearch to use an enhanced for loop. public int seqSearch2(int[] arr, int target) { for (int j : arr) { if (j == target) { return j; } } return -1; } Which of the following best describes the difference in the behavior of seqSearch2 relative to seqSearch as a result of the modification?

E. The modification in seqSearch2 will cause the value of target to be returned instead of the index of target in cases where target appears in arr.

Consider the following class declaration. public class VetRecord { private String name; private int age; private int weight; private boolean needsVaccine; public VetRecord(String nameP, int ageP, int weightP, boolean needsVaccineP) { name = nameP; age = ageP; weight = weightP; needsVaccine = needsVaccineP; } public VetRecord(String nameP, int ageP, int weightP) { name = nameP; age = ageP; weight = weightP; needsVaccine = true; } } A new constructor is to be added to the VetRecord class. Which of the following is NOT a possible header for the new constructor?

E. VetRecord(String nameP, int weightP, int ageP)

Consider the following code segment. ArrayList<Integer> vals = new ArrayList<Integer>(); vals.add(vals.size(), vals.size()); vals.add(vals.size() - 1, vals.size() + 1); vals.add(vals.size() - 2, vals.size() + 2); System.out.println(vals.toString()); What is printed as a result of executing the code segment?

E. [4, 2, 0]

Assume that the int variables a, b, c, and low have been properly declared and initialized. The code segment below is intended to print the sum of the greatest two of the three values but does not work in some cases. if (a > b && b > c) { low = c; } if (a > b && c > b) { low = b; } else { low = a; } System.out.println(a + b + c - low); For which of the following values of a, b, and c does the code segment NOT print the correct value?

E. a = 3, b = 2, c = 1

Consider the following method, which takes as input a temperature in degrees Fahrenheit and returns the corresponding temperature in degrees Celsius. public double fahrenheitToCelsius(double f) { double c = (f - 32) * 5 / 9; return c; } Assume that each of the following code segments appears in a method in the same class as fahrenheitToCelsius. Which of the following code segments prints the temperature in degrees Celsius that corresponds to 32 degrees Fahrenheit?

E. double f = 32.0; double c = fahrenheitToCelsius(f); System.out.println(c);

Consider the following class. public class Purchase { private double purchase; private double tax; public Purchase(double purchaseAmt, double taxAmt) { purchase = purchaseAmt; tax = taxAmt; } public void totalAmount() { System.out.print(purchase + tax); } } Assume that a Purchase object p has been properly declared and initialized. Which of the following code segments will successfully print the total purchase amount associated with p?

E. p.totalAmount();

SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. A set of classes using inheritance is used to represent animals observed at a wildlife sanctuary. A portion of the class hierarchy is shown in the following diagram. All Animal objects have the following attributes. A String variable indicating whether the animal is a carnivore or a herbivore A String variable representing the animal species (e.g., lion, giraffe, zebra) A String variable representing the name of the individual animal (e.g., Lisa, Gary, Percy) The Animal class also contains a toString method that indicates the state of an animal. The following table shows the intended behavior of the Animal class. StatementResultAnimal lisa = new Animal("carnivore", "lion", "Lisa");A new Animal object is created.lisa.toString();The string "Lisa the lion is a carnivore" is returned. (a) Write the complete Animal class. Your implementation must meet all specifications and conform to the behavior shown in the table. The Herbivore class is a subclass of Animal. The Herbivore class does not contain any attributes or methods other than those found in the Animal class. The constructor to the Herbivore class accepts two parameters for the species and name of the herbivore. The constructor passes those parameters along with the string literal "herbivore" to the Animal class to construct the object. The following table shows the intended behavior of the Herbivore class. StatementResultHerbivore gary = new Herbivore("giraffe", "Gary");A new Herbivore object is created.gary.toString();The string "Gary the giraffe is aherbivore" is returned. (b) Write the complete Herbivore class. Your implementation must meet all specifications and conform to the behavior shown in the table. The Elephant class is a subclass of Herbivore. The Elephant class contains one additional attribute not found in Herbivore: a double variable representing the length of the elephant's tusks, in meters. The constructor to the Elephant class accepts two parameters for the name and tusk length of the elephant. The constructor passes those parameters along with the string literal "elephant" to the Herbivore class to construct the object. The following table shows the intended behavior of the Elephant class. StatementResultElephant percy = new Elephant("Percy", 2.0);A new Elephant object is created.percy.toString();The string "Percy the elephant is aherbivore with tusks 2.0 meters long" is returned. (c) Write the complete Elephant class. Your implementation must meet all specifications and conform to the behavior shown in the table.

answers below

SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. The following Book class is used to represent books and print information about each book. Each Book object has attributes for the book title and for the name of the book's author. public class Book { private String title; private String author; public Book(String t, String a) { title = t; author = a; } public void printBookInfo() { System.out.print(title + ", written by " + author); } } (a) The PictureBook class is a subclass of the Book class that has one additional attribute: a String variable named illustratorthat is used to represent the name of the illustrator of a picture book. The PictureBook class also contains a printBookInfomethod to print the title, writer, and illustrator of a picture book. Consider the following code segment. PictureBook myBook = new PictureBook("Peter and Wendy", "J.M. Barrie", "F.D. Bedford"); myBook.printBookInfo(); The code segment is intended to print the following output. Peter and Wendy, written by J.M. Barrie and illustrated by F.D. Bedford Complete the PictureBook class below. Your implementation should conform to the example above. public class PictureBook extends Book Consider the following books. A book titled Frankenstein, written by Mary Shelley A picture book titled The Wonderful Wizard of Oz, written by L. Frank Baum and illustrated by W.W. Denslow The following code segment is intended to represent the two books described above as objects book1 and book2, respectively, and add them to the ArrayList myLibrary. ArrayList<Book> myLibrary = new ArrayList<Book>(); /* missing code */ myLibrary.add(book1); myLibrary.add(book2); (b) Write a code segment that can be used to replace /* missing code */ so that book1 and book2 will be correctly created and added to myLibrary. Assume that class PictureBook works as intended, regardless of what you wrote in part (a). The BookListing class is used to generate a descriptive listing for a book. The BookListing constructor takes a Book object and a double value as parameters and uses them to print information about the book, along with its price. Assume that book1 and book2 were created as specified in part (b). The following table demonstrates the intended behavior of the BookListing class using objects book1 and book2. Code SegmentResult PrintedBookListing listing1 = new BookListing(book1, 10.99);listing1.printDescription();Frankenstein, written by Mary Shelley, $10.99BookListing listing2 = new BookListing(book2, 12.99);listing2.printDescription();The Wonderful Wizard of Oz, written by L. Frank Baum and illustrated by W.W. Denslow, $12.99 (c) Complete the BookListing class below. Your implementation should conform to the examples. Assume that class PictureBookworks as intended, regardless of what you wrote in part (a). public class BookListing

answers below

Instance variables

attributes of an object defined within a class

Why is it necessary to select test data?

because not every possible input can be tested

A ________ is a piece of code enclosed in a {} pair.

block

1. SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. An array of String objects, words, has been properly declared and initialized. Each element of words contains a String consisting of lowercase letters (a-z). Write a code segment that uses an enhanced for loop to print all elements of words that end with "ing". As an example, if words contains {"ten", "fading", "post", "card", "thunder", "hinge", "trailing", "batting"}, then the following output should be produced by the code segment. fading trailing batting Write the code segment as described above. The code segment must use an enhanced for loop to earn full credit.

for (String str : words) { if(str.substring(str.length - 3).equals("ing")) { System.out.println(str); } |

SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. An array of String objects, words, has been properly declared and initialized. Each element of words contains a String consisting of lowercase letters (a-z). Write a code segment that uses an enhanced for loop to print all elements of words that end with "ing". As an example, if words contains {"ten", "fading", "post", "card", "thunder", "hinge", "trailing", "batting"}, then the following output should be produced by the code segment. fading trailing batting Write the code segment as described above. The code segment must use an enhanced for loop to earn full credit.

for (String str : words) { if(str.substring(str.length - 3).equals("ing")) { System.out.println(str); } }

What is the format for a for-each loop? (for an array)

for (type [] name : NameOfArray)

If you're using bottom-up development, what is the first thing you need to do?

for each method in a class, list all the other classes needed to implement that method

Name the two control structures that allow the computer to perform iterative tasks.

for loop and while loop

The following is known as what kind of loop? for (SomeType element : collection) { statements; }

for-each

Part C: Write a statement that will be used to update the gradShow light sequence to "0011 0011 0011". Write the statement below.

gradShow.changeSequence("0011 0011 0011");

Part B: Write a statement that will call the display method to display the light sequence for the gradShow object. Write the statement below.

gradShow.display();

When designing a program, after you identify necessary methods, what do you do?

group the methods into classes

Question 1 Item 1 Question 1 SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. This question involves the creation of user names for an online system. A user name is created based on a user's first and last names. A new user name cannot be a duplicate of a user name already assigned. You will write the constructor and one method of the UserName class. A partial declaration of the UserName class is shown below. public class UserName { // The list of possible user names, based on a user's first and last names and initialized by the constructor. private ArrayList<String> possibleNames; /** Constructs a UserName object as described in part (a). * Precondition: firstName and lastName have length greater than 0 * and contain only uppercase and lowercase letters. */ public UserName(String firstName, String lastName) { /* to be implemented in part (a) */ } /** Returns true if arr contains name, and false otherwise. */ public boolean isUsed(String name, String[] arr) { /* implementation not shown */ } /** Removes strings from possibleNames that are found in usedNames as described in part (b). */ public void setAvailableUserNames(String[] usedNames) { /* to be implemented in part (b) */ } } (a) Write the constructor for the UserName class. The constructor initializes and fills possibleNames with possible user names based on the firstName and lastNameparameters. The possible user names are obtained by concatenating lastName with different substrings of firstName. The substrings begin with the first character of firstNameand the lengths of the substrings take on all values from 1 to the length of firstName. The following example shows the contents of possibleNames after a UserName object has been instantiated. Example UserName person = new UserName("john", "smith"); After the code segment has been executed, the possibleNames instance variable of person will contain the following String objects in some order. "smithj", "smithjo", "smithjoh", "smithjohn" Write the UserName constructor below. /** Constructs a UserName object as described in part (a). * Precondition: firstName and lastName have length greater than 0 * and contain only uppercase and lowercase letters. */ public UserName(String firstName, String lastName)

if(this.isValid(firstName) && this.isValidName(lastName)) { possibleNames = new ArrayList<String>(); for(int i = 1,; i < firstName.length; i++) { possibleNames.add(lastName+firstName.substring(0,i)); } } else { System.out.println("firstName and lastName must contain letters only."); }

In polymorphism, the compiler deterimes __ a method can be called, and the run-time environment determines ___ a method can be called

if, how

A concrete class that implements an interface must do what?

implement every method in the interface

Interfaces are implemented using what keyword?

implements

When did the waterfall model of software development come about?

in the 1960s

If super is used in the implementation of a subclass constructor, it must be used...

in the first line of the constructor body

What does it mean if you use a bottom-up approach?

independent classes are fully implemented and tested before being incorporated into the overall project

In what order are classes implemented when using the bottom-up method?

independent classes first, then classes that depend on just one other class, and so on

index

indicates the position of a character in a string, i.e. in the string abcde, a has an index of 0 and b of 1

What two kinds of relationships between classes should you consider when designing a program?

inheritance and composition

A subclass can itself be a superclass for another subclass, leading to a(n)...

inheritance hierarchy

Small arrays whose values are known can be declared with a(n)...

initializer list

increment operator

instructs Java to add one to a variable's current value and reassign the result to the variable; ++

decrement operator

instructs Java to subtract one from a variable's current value and reassign the result to the variable; --

Part A: Advance

public class Advance extends Ticket { private int dia; public Advance(int days) { super(); dia = days; } public double getPrice() { if(dia >= 10) { return 30.0; } else { return 40.0; } } }

(c) The programmer would like to add a method called getAllGroupAssignments that returns a list of assignments that have been designated as having parts where students worked in groups. A group assignment can appear in any category. Write a description of how you would change the Assignment and StudentAssignments classes in order to support this modification. Make sure to include the following in your response. Write the method header for the getAllGroupAssignments method. Identify any new or modified variables, constructors, or methods aside from the getAllGroupAssignments method. Do not write the program code for this change. Describe, for each new or revised variable, constructor, or method, how it would change or be implemented, including visibility and type. You do not need to describe the getAllGroupAssignments method. Do not write the program code for this change.

public ArrayList<Assignment> getAllGroupAssignments() The Assignment class would have to be changed to have a private boolean value inGroup which returns either true or false depending on if students worked in groups. The Assignment class should also include a public getGroups() method which returns the groups the students worked in. The StudentAssignments class should include the getAllGroupAssignments() method because it has an array list of Assignment objects which can be iterated through.

(b) Write the availableMechanics method, which returns an ArrayList containing the mechanic numbers of all available mechanics. If there is no available mechanic, an empty list is returned. A mechanic is available if the mechanic's identifier does not appear in schedule. Suppose schedule has the following contents. For these contents of schedule, availableMechanic should return an ArrayList containing the values 2, 3, 4, and 5 (in any order). Complete the availableMechanics method. Assume that addRepair works as specified, regardless of what you wrote in part (a). /** Returns an ArrayList containing the mechanic identifiers of all available mechanics, * as described in part (b). */ public ArrayList<Integer> availableMechanics()

public ArrayList<Integer> availableMechanics() { ArrayList<Integer> availableList = new ArrayList<Integer>(); for(int i = 0; i < numberOfMechanics; i++) { int count = 0; for(CarRepair c : schedule) { if(c.getMechanicNum() = i) { count++; } } if(count == 0) { availableList.add(i); } } return availableList; }

(c) A programmer would like to add a method called getMostLuggageCapacity, which returns a Flight object that can carry the greatest amount of luggage, by weight. Write a description of how you would change the Flight and Airport classes in order to support this modification. Make sure to include the following in your response. Write the method header for the getMostLuggageCapacity method. Identify any new or modified variables, constructors, or methods aside from the getMostLuggageCapacity method. Do not write the program code for this change. Describe, for each new or revised variable, constructor, or method, how it would change or be implemented, including visibility and type. You do not need to describe the implementation of the getMostLuggageCapacity method. Do not write the program code for this change.

public Flight getMostLuggageCapacity() The Flight class would have to be changed by adding a private instance variable luggage and a public getLuggage() method. This method should return the amount of luggage carried by a flight. The Airport class would be where the getMostLuggageCapacity() method would be added because it has an array list of Flight objects. This list can then be iterated over to compare each flight's luggage capacity.

Consider the following class that represents the test results of a group of students that took a multiple-choice test. Write the TestResults method highestScoringStudent, which returns the name of the student who received the highest score on the test represented by the parameter key. If there is more than one student with the highest score, the name of any one of these highest-scoring students may be returned. You may assume that the size of each answer sheet represented in the ArrayList sheets is equal to the size of the ArrayList key. In writing highestScoringStudent, assume that getScore works as specified, regardless of what you wrote in part (a). Complete method highestScoringStudent below

public String highestScoringStudent(ArrayList<String> key) { StudentAnswerSheet highestScorer = sheets.get(0); for(StudentAnswerSheet sheet : sheets) { if(sheet.getScore(key) > highestScorer.getScore(key)) { highestScorer = sheet; } } return highestScorer.getName();}

(a) Write the addRepair method. The method attempts to schedule a repair by the mechanic with identifier m in the bay with identifier b. The repair can be scheduled if mechanic m and bay b are both available. A mechanic is available if the given mechanic number does not appear in an element of schedule and a bay is available if the given bay number does not appear in an element of schedule. If the mechanic and bay are both available, the addRepair method adds the repair to schedule and returns true. If either the mechanic or the bay are not available, the addRepair method returns false. The following sequence of statements provides examples of the behavior of the addRepair method. The statement RepairSchedule r = new RepairSchedule(6); constructs a new RepairSchedule object r. No repairs have been scheduled. Mechanics are numbered 0 through 5. The call r.addRepair(3, 4) returns true because neither mechanic 3 nor bay 4 are present in schedule. The contents of schedule after the call are as follows. The call r.addRepair(0, 1) returns true because neither mechanic 0 nor bay 1 are present in schedule. The contents of schedule after the call are as follows. The call r.addRepair(0, 2) returns false because mechanic 0 is present in schedule. The contents of schedule after the call are as follows. The call r.addRepair(2, 4) returns false because bay 4 is present in schedule. The contents of schedule after the call are as follows. The call r.carOut(4) removes the repair in bay 4 from schedule. The carOut method is shown here to illustrate that bays and mechanics become available when car repairs are complete. You do not need to write or call this method. The contents of schedule after the call are as follows. The call r.addRepair(1, 4) returns true because neither mechanic 1 nor bay 4 are present in schedule. The contents of schedule after the call are as follows. Complete the addRepair method. /** Attempts to schedule a repair by a given mechanic in a given bay as described in part (a). * Precondition: 0 <= m < numberOfMechanics and b >= 0 */ public boolean addRepair(int m, int b)

public boolean addRepair (int m, int b) { for(CarRepair c : schedule) { if(c.getMechanicNum() == m) || c.getBayNum == b) { return false; } } schedule.add(new CarRepair(m, b)); return true; }

(a) Write the Airport method getTotalRevenue. The method returns the total revenue for all flights into and out of the airport. Revenue for a flight is the product of the number of passengers on the flight and the price of a seat on the flight. All seats on a flight have the same price. Some flights sell more seats than there is capacity for, since passengers sometimes cancel or modify reservations. If there are more passengers on a flight than the flight has capacity for, the revenue for the flight is the product of the capacity and the price of a seat on the flight. For example, assume that capitalHub has been declared as an Airport object and ArrayList allFlights contains the following flights. Number of Passengers: 25Price: 50.00Capacity: 30Number of Passengers: 10Price: 100.50Capacity: 60Number of Passengers: 50Price: 200.00Capacity: 40Number of Passengers: 20Price: 100.00Capacity: 120 The following table shows the revenue that would be generated by each flight in allFlights. Number of PassengersPrice of a SeatCapacityRevenue Calculation2525$50.00$50.00303025×$50.00=$1,250.0025×$50.00=$1,250.001010$100.50$100.50606010×$100.50=$1,005.0010×$100.50=$1,005.005050$200.00$200.00404040×$200.00=$8,000.0040×$200.00=$8,000.002020$100.00$100.0012012020×$100.00=$2,000.0020×$100.00=$2,000.00 The call capitalHub.getTotalRevenue() should return the value 12255.0. Complete method getTotalRevenue. /** Returns the revenue generated by all flights at the airport, as described in part (a) */ public double getTotalRevenue()

public double getTotalRevenue() { double totalRev = 0; for(Flight f : allFlights) { if(f.getNumPassengers() > f.getCapacity()) { totalRev += f.getPrice() * f.getCapacity(); } else { totalRev += f.getPrice() * f.getNumPassengers(); } } return totalRev; }

(a) Write the StudentAssignments method getNumberOfAs. The method returns the number of assignments in a given category that have a grade greater than or equal to 90. Complete method getNumberOfAs. /** Returns the number of assignments in a given category that have a grade greater than or * equal to 9090, as described in part (a) */ public int getNumberOfAs(String cat)

public int getNumberOfAs(String cat) { int count = 0; for(Assignment a : assignmentList) { if(a.getGrade() >= 90 && a.getCategory().equals(cat)) { count++; } } return count; }

Question 2 Sparse Array Part A: getValueAt Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.Notes: Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. A two-dimensional array of integers in which most elements are zero is called a sparse array. Because most elements have a value of zero, memory can be saved by storing only the non-zero values along with their row and column indexes. The following complete SparseArrayEntry class is used to represent non-zero elements in a sparse array. A SparseArrayEntry object cannot be modified after it has been constructed. The SparseArray class represents a sparse array. It contains a list of SparseArrayEntry objects, each of which represents one of the non-zero elements in the array. The entries representing the non-zero elements are stored in the list in no particular order. Each non-zero element is represented by exactly one entry in the list. The following table shows an example of a two-dimensional sparse array. Empty cells in the table indicate zero values. The sample array can be represented by a SparseArray object, sparse, with the following instance variable values. The items in entries are in no particular order; one possible ordering is shown below. (a) Write the SparseArray method getValueAt. The method returns the value of the sparse array element at a given row and column in the sparse array. If the list entries contains an entry with the specified row and column, the value associated with the entry is returned. If there is no entry in entries corresponding to the specified row and column, 0 is returned.In the example above, the call sparse.getValueAt(3, 1) would return -9, and sparse.getValueAt(3, 3) would return 0. Complete method getValueAt below. (b) Write the SparseArray method removeColumn. After removing a specified column from a sparsearray: All entries in the list entries with column indexes matching col are removed from the list. All entries in the list entries with column indexes greater than col are replaced by entries with column indexes that are decremented by one (moved one column to the left). The number of columns in the sparse array is adjusted to reflect the column removed. The sample object sparse from the beginning of the question is repeated for your convenience. The shaded entries in entries, below, correspond to the shaded column above. When sparse has the state shown above, the call sparse.removeColumn(1) could result insparse having the following values in its instance variables (since entries is in no particular order, itwould be equally valid to reverse the order of its two items). The shaded areas below show the changes.

public int getValueAt(int row, int col) { for(SparseArrayEntry e : entries) { if(e.getRow() == row && e.getCol() == col) { return e.getValue(); } } return 0; }

Part B: removeColumn Write the SparseArray method removeColumn. After removing a specified column from a sparsearray: All entries in the list entries with column indexes matching col are removed from the list. All entries in the list entries with column indexes greater than col are replaced by entries with column indexes that are decremented by one (moved one column to the left). The number of columns in the sparse array is adjusted to reflect the column removed. The sample object sparse from the beginning of the question is repeated for your convenience. The shaded entries in entries, below, correspond to the shaded column above. When sparse has the state shown above, the call sparse.removeColumn(1) could result insparse having the following values in its instance variables (since entries is in no particular order, itwould be equally valid to reverse the order of its two items). The shaded areas below show the changes.

public void removeColumn(int col) { int i = 0; while(i < entries.size()) { SparseArrayEntry e = entries.get(i); if(e.getCol() == col) { entries.remove(i); } else if(e.getCol() > col) { entries.set(i, new SparseArrayEntry(e.getRow(), e.getCol() - 1, e.getValue())); i++; } else { i++; } } numCols--; }

(b) Write the Airport method updateFlights. The method removes from the ArrayList allFlights any flight where the number of passengers is less than 2020 percent of the total capacity. The method should return the total number of passengers whose flight was removed. For example, assume that capitalHub has been declared as an Airport object and ArrayList allFlights contains the following flights. Number of Passengers: 25Price: 50.00Capacity: 30Number of Passengers: 10Price: 100.50Capacity: 60Number of Passengers: 50Price: 200.00Capacity: 40Number of Passengers: 20Price: 100.00Capacity: 120 The call capitalHub.updateFlights() should return the value 30, and after the method finished executing, the ArrayList allFlights should contain the following two flights. Number of Passengers: 25Price: 50.00Capacity: 30Number of Passengers: 50Price: 200.00Capacity: 40 Complete method updateFlights. /** Updates the list of flights by removing certain flights and returns the total number of * passengers whose flights were removed, as described in part (b) */ public int updateFlights()

public int updateFlights() { int sum = 0; for(int k = allFlights.size() - 1; k >= 0; k--) { Flight temp = allFlights.get(k); int min = (int) (temp.getCapacity() * .2); int pass = temp.getNumPassengers(); if(pass < min) { sum+= pass; allFlights.remove(k); } } return sum; }

Part C: isDiverse A two-dimensional array is diverse if no two of its rows have entries that sum to the same value. In the following examples, the array mat1 is diverse because each row sum is different, but the array mat2 is not diverse because the first and last rows have the same sum. Write a static method isDiverse that determines whether or not a given two-dimensional array is diverse. The method has one parameter: a two-dimensional array arr2D of int values. The method should return true if all the row sums in the given array are unique; otherwise, it should return false. In the arrays shown above, the call isDiverse (mat1) returns true and the call isDiverse(mat2) returns false. Assume that arraySum and rowSums work as specified, regardless of what you wrote in parts (a) and(b). You must use rowSums appropriately to receive full credit.Complete method isDiverse below. / * * Returns true if all rows in arr2D have different row sums;* false otherwise. * /public static boolean isDiverse(int [ ] [ ] arr2D)

public static boolean isDiverse(int[][] arr2D) { int[] sums = rowSums(arr2D); for(int i = 0; i < sums.length; i++) { for(int j = i+1; i < sums.length; j++) { if(sums[i]==sums[j]) { return false; } } } return true; }

Part A: arraySum Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA.Notes: Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. This question involves reasoning about one-dimensional and two-dimensional arrays of integers. You will write three static methods, all of which are in a single enclosing class, named DiverseArray (not shown). The first method returns the sum of the values of a one-dimensional array; the second method returns an array that represents the sums of the rows of a two-dimensional array; and the third method analyzes row sums. (a) Write a static method arraySum that calculates and returns the sum of the entries in a specified one-dimensional array. The following example shows an array arr1 and the value returned by a call to arraySum. Complete method arraySum below. / * * Returns the sum of the entries in the one-dimensional array arr. * / public static int arraySum (int [ ] arr) (b) Write a static method rowSums that calculates the sums of each of the rows in a given two-dimensional array and returns these sums in a one-dimensional array. The method has one parameter, a two-dimensional array arr2D of int values. The array is in row-major order: arr2D [ r ] [ c ] is the entry at row r and column c. The method returns a one-dimensional array with one entry for each row of arr2D such that each entry is the sum of the corresponding row in arr2D. As a reminder, each row of a two-dimensional array is a one-dimensional array.For example, if mat1 is the array represented by the following table, the call rowSums(mat1) returns the array {16, 32, 28, 20}. Assume that arraySum works as specified, regardless of what you wrote in part (a). You must use arraySum appropriately to receive full credit. Complete method rowSums below. / * * Returns a one-dimensional array in which the entry at index k is the sum of * the entries of row k of the two-dimensional array arr2D. * / public static int [ ] rowSums(int [ ] [ ] arr2D) (c) A two-dimensional array is diverse if no two of its rows have entries that sum to the same value. In the following examples, the array mat1 is diverse because each row sum is different, but the array mat2 is not diverse because the first and last rows have the same sum. Write a static method isDiverse that determines whether or not a given two-dimensional array is diverse. The method has one parameter: a two-dimensional array arr2D of int values. The method should return true if all the row sums in the given array are unique; otherwise, it should return false. In the arrays shown above, the call isDiverse (mat1) returns true and the call isDiverse(mat2) returns false. Assume that arraySum and rowSums work as specified, regardless of what you wrote in parts (a) and(b). You must use rowSums appropriately to receive full credit.Complete method isDiverse below. / * * Returns true if all rows in arr2D have different row sums;* false otherwise. * /public static boolean isDiverse(int [ ] [ ] arr2D)

public static int arraySum(int[] arr) { int sum = 0; for(int elem : arr) { sum += elem; } return sum; }

Part B: rowSums Write a static method rowSums that calculates the sums of each of the rows in a given two-dimensional array and returns these sums in a one-dimensional array. The method has one parameter, a two-dimensional array arr2D of int values. The array is in row-major order: arr2D [ r ] [ c ] is the entry at row r and column c. The method returns a one-dimensional array with one entry for each row of arr2D such that each entry is the sum of the corresponding row in arr2D. As a reminder, each row of a two-dimensional array is a one-dimensional array.For example, if mat1 is the array represented by the following table, the call rowSums(mat1) returns the array {16, 32, 28, 20}. Assume that arraySum works as specified, regardless of what you wrote in part (a). You must use arraySum appropriately to receive full credit. Complete method rowSums below. / * * Returns a one-dimensional array in which the entry at index k is the sum of * the entries of row k of the two-dimensional array arr2D. * / public static int [ ] rowSums(int [ ] [ ] arr2D)

public static int[] rowSums(int[][] arr2D) { int[] sums = new int[arr2D.length]; int rowNum = 0; for(int[] row : arr2D) { sums[rowNum] = arraySum(row); rowNum++; } return sums; }

Part C: Kennel - allSpeak

public void allSpeak() { for(int i = 0; i < petList.size(); i++) { System.out.println(petList.get(i).getName() + " " + petList.get(i).speak()); }

2b.

public void computeWages(double fixedWage, double perItemWage) { double threshold = computeBonusThreshold(); for(int i = 0; i < itemsSold.length; i++) { double baseWage = fixedWage + perItemWage * itemsSold[i]; if(itemsSold[i] > threshold) { wages[i] = baseWage * 1.1; } else { wages[i] = baseWage; } } }

Question 2 part B: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN JAVA. Assume that the classes listed in the Java Quick Reference have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods will not receive full credit. Employees at a store are paid daily wages according to the following rules. Each employee is paid the same fixed amount per day. Each employee is paid an additional amount for each item they sold on that day. Daily Bonus:If the number of items sold that day by an employee is greater than a computed threshold, then the employee also receives a bonus equal to 1010 percent of the employee's daily wages. You will write two methods in the Payroll class below. public class Payroll { private int[] itemsSold; // number of items sold by each employee private double[] wages; // wages to be computed in part (b) /** Returns the bonus threshold as described in part (a). */ public double computeBonusThreshold() { /* To be implemented in part (a) */ } /** Computes employee wages as described in part (b) * and stores them in wages. * The parameter fixedWage represents the fixed amount each employee * is paid per day. * The parameter perItemWage represents the amount each employee * is paid per item sold. */ public void computeWages(double fixedWage, double perItemWage) { /* To be implemented in part (b) */ } // Other instance variables, constructors, and methods not shown. } The bonus threshold is calculated based on the number of items sold by all employees on a given day. The employee with the greatest number of sales and the employee with the least number of sales on that day are ignored in the calculation. The average number of items sold by the remaining employees on that day is computed, and this value is used as the bonus threshold. For a given day, the number of items sold by each employee is stored in the array itemsSold. The example below shows the contents of itemsSold for a day in which there were ten employees. Each array index represents an individual employee. For example, itemsSold[3] represents the number of items sold by employee 3. Based on the information in the table, the bonus threshold is calculated as follows. (48+50+37+62+38+70+55+37+64+60)−37−708=51.75(48+50+37+62+38+70+55+37+64+60)−37−708=51.75 (a) Complete the method computeBonusThreshold below, which is intended to return the bonus threshold based on the contents of the itemsSold array. Assume that itemsSold has been filled appropriately, and that the array contains at least three employees. /** Returns the bonus threshold as described in part (a). */ public double computeBonusThreshold() The computeWages method is intended to calculate the wages for each employee and to assign them to the appropriate element of the array wages. For example, wages[3] should be assigned the wages for employee33. An employee's wages consist of their daily wages plus a possible bonus and are calculated as follows. Each employee's wages are equal to the fixed wage plus the number of items sold times the amount paid per item sold. If the employee sold more items than the bonus threshold, the employee also receives a 1010 percent bonus added to their wages. As described in part (a), computeBonusThreshold() returns 51.75 for the example array below. Suppose that fixedWage is 10.0 and perItemWage is 1.5. Employee 00 did not sell more items than the bonus threshold, so employee 00's wages are equal to 10.0 + 1.5 * 48, which evaluates to 82.0. This value will be assigned to wages[0]. Employee 99 sold more items than the bonus threshold, so employee 99 receives a 1010 percent bonus. Employee 99's wages are equal to (10.0 + 1.5 * 60) * 1.1, or 110.0. This value will be assigned to wages[9]. (b) Write the method computeWages. Assume that itemsSold has been filled appropriately, and there are at least three employees in the array. Assume also that the wages array and the itemsSold array have the same length. Your solution must call computeBonusThreshold appropriately to receive full credit. /** Computes employee wages as described in part (b) * and stores them in wages. * The parameter fixedWage represents the fixed amount each employee * is paid per day. * The parameter perItemWage represents the amount each employee * is paid per item sold. */ public void computeWages(double fixedWage, double perItemWage)

public void computeWages(double fixedWage, double perItemWage) { double threshold = computeBonusThreshold(); for(int i = 0; i < itemsSold.length; i++) { double baseWage = fixedWage + perItemWage * itemsSold[i]; if(itemsSold[i] > threshold) { wages[i] = baseWage * 1.1; } else { wages[i] = baseWage; } } }

What does E get(int index) do?

returns the element at the specified index in the list

What does the equals method do in the Integer class? ex: boolean equals(Object obj)

returns true only if the Integer has the same int value as obj.

Question 2 (b) Write the UserName method setAvailableUserNames. The method removes from possibleNames all names that are found in usedNames. These represent user names that have already been assigned in the online system and are therefore unavailable. A helper method, isUsed, has been provided. The isUsed method searches for name in arr. The method returns true if an exact match is found and returns false otherwise. The example below shows the intended behavior of the setAvailableUserNames method. StatementStrings in possibleNames ​after statement executionString[] used = {"harta", "hartm", "harty"}; UserName person2 = new UserName("mary", "hart");"hartm", "hartma","hartmar", "hartmary"​person2.setAvailableUserNames(used);"hartma", "hartmar", "hartmary"​ Assume that the constructor works as specified, regardless of what you wrote in part (a). You must use isUsed appropriately to receive full credit. Complete the setAvailableUserNames method below. /** Removes strings from possibleNames that are found in usedNames as described in part (b). */ public void setAvailableUserNames(String[] usedNames)

public void setAvailableUserNames(String[] usedNames) { for(int i = 0; i < possibleNames.size(); i++) { if(isUsed(possibleNames.get(i), usedNames)) { possibleNames.remove(i); i--; } } }

(b) Write the StudentAssignments method updateGrade. The method replaces one and only one grade below 7070 in a given category, if any such grade exists and if the given category has more than five assignments with a grade of A. The identified grade is replaced with the value 7070. If more than one such assignment exists, the grade of any one of those assignments may be replaced. Assume that getNumberOfAs works as specified, regardless of what you wrote for part (a). You must use getNumberOfAs appropriately to receive full credit. Complete method updateGrade. /** Replaces a single assignment grade in a given category if the number of As in * the category is greater than 55 but at least one score is below 7070, as described in part (b) */ public void updateGrade(String cat)

public void updateGrade(String cat) { int aCount = getNumberOfAs(cat); if(aCount > 5) { for(Assignment a : assignmentList) { if(a.getGrade() < 70 && a.getCategory().equals(cat)) { a.setGrade(70); return; } } } }

When a block is exited, the memory for a local variable is...

recycled

Whereas double, int, char and boolean are primitive data types, all objects are ______ data types.

reference

identity equality

refers to whether two objects are actually the same object

_____________ operators are used in boolean expressions.

relational

When using a for-each loop to traverse an array, what can you NOT do?

replace the value

character literals

represented by a single keyboard character and are enclosed in single quotes

boolean data type

restricted to logical values (true/false)

A constructor has no...

return type


Related study sets

NICET Level 1 Fire Alarm Systems

View Set

EXAM 4 OB Chapter 17: Labor and Birth Complications NCLEX

View Set

Prep U: musculoskeletal disorders

View Set