godsent

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

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?

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

Consider the following code segment. int j = 1; while (j <= 5) { for (int k = 4; k > 1; k--) { System.out.println("ha"); // line 6 } j++; } How many times will the print statement on line 6 execute?

15

Consider the following code segment. int count = 0; int number = 20; while (number > 0) { number = number / 2; count++; } What will be the value of count after executing the code segment?

5

Consider the following code segment. int a = 100; while (a > 1) { System.out.println("$"); a /= 2; } How many $'s are printed as a result of executing the code segment?

6

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

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

Consider the following two code segments. I. int[] arr = {1, 2, 3, 4, 5}; for (int x = 0; x < arr.length; x++) { System.out.print(arr[x + 3]); } II. int[] arr = {1, 2, 3, 4, 5}; for (int x : arr) { System.out.print(x + 3); } Which of the following best describes the behavior of code segment I and code segment II ?

Code segment I will cause an ArrayIndexOutOfBoundsException and code segment II will print 45678.

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

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

Consider the following method. public int[] transform(int[] a) { a[0]++; a[2]++; return a; } The following code segment appears in a method in the same class as transform. /* missing code */ arr = transform(arr); After executing the code segment, the array arr should contain {1, 0, 1, 0}. Which of the following can be used to replace /* missing code */ so that the code segment works as intended? int[] arr = {0, 0, 0, 0}; int[] arr = new int[0]; int[] arr = new int[4];

I and III

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 { // 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" ? when obj references an object of type ParentClass when obj references an object of type SubClass when obj references an object of type SubSubClass

II only

Consider the following code segment where num is a properly declared integer initialized to a positive value. int total = 0; while (num > 0) { total += num % 10; num /= 10; } Which of the following code segments could replace the while loop without changing the resulting value of total?

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

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

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?

Line 3 causes a compile-time error because the variable sec needs to be declared as type Second to call output.

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?

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?

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

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

The variable myBook is assigned a reference to a new Book object created using the one-argument Book constructor, which uses super to set myBook's title attribute to "Adventure Story". The variable yourBook is assigned a reference to a new Book object created using super to call to the Publication no-argument constructor to set yourBook's title attribute to "Generic".

Consider the following code segment. int n = 6; for (int i = 1; i < n; i = i + 2) // Line 2 { System.out.print(i + " "); } Which of the following best explains how changing i < n to i <= n in line 2 will change the result?

There will be no change to the program output because the loop will iterate the same number of times.

Consider the following code segment. int a = 1; while (a <= 2) { int c = 1; while (/* missing condition */) { System.out.print("*"); c++; } a++; } The code segment is intended to print "******". Which of the following can be used to replace /* missing condition */ so that the code segment works as intended?

c <= 3

Consider the following code segment. for (int k = 0; k < 4; k++) { /* missing loop header */ { System.out.print(k); } System.out.println(); } The code segment is intended to produce the following output. 0 11 222 3333

for (int h = k; h >= 0; h--)

In the code segment below, assume that the int array numArr has been properly declared and initialized. The code segment is intended to reverse the order of the elements in numArr. For example, if numArr initially contains {1, 3, 5, 7, 9}, it should contain {9, 7, 5, 3, 1} after the code segment executes. /* missing loop header */ { int temp = numArr[k]; numArr[k] = numArr[numArr.length - k - 1]; numArr[numArr.length - k - 1] = temp; } Which of the following can be used to replace /* missing loop header */ so that the code segment works as intended?

for (int k = 0; k < numArr.length / 2; k++)

Consider the following code segment. int total = 0; for (int k = 0; k <= 100; k += 2) { total += k; } Which of the following for loops could be used to replace the for loop in the original code segment so that the original and the revised code segments store the same value in total?

for (int k = 1; k <= 101; k += 2) { total += k - 1; }

Consider the following class definition. public class Beverage { private int numOunces; private static int numSold = 0; public Beverage(int numOz) { numOunces = numOz; } public static void sell(int n) { /* implementation not shown */ } } Which of the following best describes the sell method's level of access to the numOunces and numSold variables?

numSold can be accessed and updated; numOunces cannot be accessed or updated.

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?

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?

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

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?

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

Consider the following code segment, which is intended to store the sum of all multiples of 10 between 10 and 100, inclusive (10 + 20 + ... + 100), in the variable total. int x = 100; int total = 0; while( /* missing code */ ) { total = total + x; x = x - 10; } Which of the following can be used as a replacement for /* missing code */ so that the code segment works as intended?

x >= 10

Consider the following code segment. int k = 35; while (k >= 0) { System.out.println("X"); k -= 5; } How many times will the string "X" be printed as a result of executing the code segment?

8

Consider the following code segment. int[] arr = {4, 3, 2, 1, 0}; int total = 0; for (int k = 0; k <= total; k++) { if (arr[k] % 2 == 0) { total += arr[k]; } else { total -= arr[k]; } } System.out.print(total); What, if anything, is printed as a result of executing the code segment?

1

Consider the following code segment. int a = 1; String result = ""; while (a < 20) { result += a; a += 5; } System.out.println(result); What, if anything, is printed as a result of executing the code segment?

161116

Consider the following code segment. String temp = "Mississippi"; String part = "si"; int position = 0; int count = 0; while(temp.indexOf(part) >= 0) { position = temp.indexOf(part); count++; temp = temp.substring(position + 1); } System.out.println(count); What, if anything, is printed as a result of executing the code segment?

2

Consider the following class definition. public class Contact { private String contactName; private String contactNumber; public Contact(String name, String number) { contactName = name; contactNumber = number; } public void doSomething() { System.out.println(this); } public String toString() { return contactName + " " + contactNumber; } } The following code segment appears in another class. Contact c = new Contact("Alice", "555-1234"); c.doSomething(); c = new Contact("Daryl", ""); c.doSomething(); What is printed as a result of executing the code segment?

Alice 555-1234 Daryl

The array fruits is declared below. String [] fruits = {"apples", "bananas", "cherries", "dates"}; Which of the following code segments will cause an ArrayIndexOutOfBoundsException ? I. for (int i = 0; i <= fruits.length; i++) { System.out.println(fruits[i]); } II. for (int i = 0; i <= fruits.length - 1; i++) { System.out.println(fruits[i]); } III. for (int i = 1; i <= fruits.length; i++) { System.out.println(fruits[i - 1]); }

I only

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 and 0 <= k */

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?

/* Precondition: m <= n */

Consider the following code segment. String str = "AP-CSA"; for (int i = 0; i < str.length(); i++) { if (str.substring(i, i + 1).equals("A")) { System.out.print(i + " "); } } What is printed as a result of executing the code segment?

0 5

Consider the following class definition. public class Person { private String name; private int feet; private int inches; public Person(String nm, int ft, int in) { name = nm; feet = ft; inches = in; } public int heightInInches() { return feet * 12 + inches; } public String getName() { return name; } public String compareHeights(Person other) { if (this.heightInInches() < other.heightInInches()) { return name; } else if (this.heightInInches() > other.heightInInches()) { return other.getName(); } else return "Same"; } } The following code segment appears in a method in a class other than Person. Person andy = new Person("Andrew", 5, 6); Person ben = new Person("Benjamin", 6, 5); System.out.println(andy.compareHeights(ben)); What, if anything, is printed as a result of executing the code segment?

Andrew

Consider the following method, which is intended to return the number of strings of length greater than or equal to 3 in an array of String objects. public static int checkString(String[] arr) { int count = 0; for (int k = 0; k < arr.length; k++) { if (arr[k].length() >= 3) { count++; } } return count; } Which of the following code segments compile without error? checkString(new String[]); checkString(new String[0]); String[] str = {"cat", "dog"};checkString(str);

II and III only

Consider the following code segment. for (int i = 0; i < 5; i++) // Line 1 { for (int j = 0; j < 5; j++) { int k = i + j; System.out.print(k + " "); } } Which of the following best describes the result of changing i < 5 to i > 5 in line 1?

Nothing will be printed because the body of the outer for loop will not execute at all.

Consider the following class definition. public class Gadget { private static int status = 0; public Gadget() { status = 10; } public static void setStatus(int s) { status = s; } } The following code segment appears in a method in a class other than Gadget. Gadget a = new Gadget(); Gadget.setStatus(3); Gadget b = new Gadget(); Which of the following best describes the behavior of the code segment?

The code segment creates two Gadget objects a and b. The class Gadget's static variable status is set to 10, then to 3, and then back to 10.

Consider the following code segments, which differ only in their loop header. Code Segment I for (int i = 0; i < 10; i++) { System.out.print( "*" ); } Code Segment II for (int i = 1; i <= 10; i++) { System.out.print( "*" ); } Which of the following best explains how the difference in the two loop headers affects the output?

The output of the code segments is the same because the loops in both code segments iterate 10 times.

Consider the following code segment. for (int j = 0; j < 4; j++) { for (int k = 0; k < j; k++) { System.out.println("hello"); } } Which of the following best explains how changing the inner for loop header to for (int k = j; k < 4; k++) will affect the output of the code segment?

The string "hello" will be printed four additional times because the inner loop will iterate one additional time for each iteration of the outer loop

Consider the following class definition. public class ClassP { private String str; public ClassP(String newStr) { String str = newStr; } } The ClassP constructor is intended to initialize the str instance variable to the value of the formal parameter newStr. Which of the following statements best describes why the ClassP constructor does not work as intended?

The variable str should not be declared as a String in the constructor.

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?

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

Consider the following class definition. public class Email { private String username; public Email(String u) { username = u; } public void printThis() { System.out.println(this); } public String toString() { return username + "@example.com"; } } The following code segment appears in a method in another class. Email e = new Email("default"); e.printThis(); What, if anything, is printed as a result of executing the code segment?

[email protected]

The code segment below is intended to set the boolean variable duplicates to true if the int array arr contains any pair of duplicate elements. Assume that arr has been properly declared and initialized. boolean duplicates = false; for (int x = 0; x < arr.length - 1; x++) { /* missing loop header */ { if (arr[x] == arr[y]) { duplicates = true; } } } Which of the following can replace /* missing loop header */ so that the code segment works as intended?

for (int y = x + 1; y < arr.length; y++)

Consider the following class. The method getTotalSalaryAndBonus is intended to return an employee's total salary with the bonus added. The bonus should be doubled when the employee has 10 or more years of service. public class Employee { private String name; private double salary; private int yearsOfService; public Employee(String n, double sal, int years) { name = n; salary = sal; yearsOfService = years; } public double getTotalSalaryAndBonus(double bonus) { /* missing code */ } } Which of the following could replace /* missing code */ so that method getTotalSalaryAndBonus will work as intended?

if (yearsOfService >= 10) { bonus *= 2; } return salary + bonus;

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 matches(Silly other) { if (other == null) { return false; } 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 ?

s3.matches(s4)

Consider the following code segment, which is intended to print the maximum value in an integer array values. Assume that the array has been initialized properly and that it contains at least one element. int maximum = /* missing initial value */; for (int k = 1; k < values.length; k++) { if (values[k] > maximum) { maximum = values[k]; } } System.out.println(maximum); Which of the following should replace /* missing initial value */ so that the code segment will work as intended?

values[0]

Consider the following incomplete code segment, which is intended to print the sum of the digits in num. For example, when num is 12345, the code segment should print 15, which represents the sum 1 + 2 + 3 + 4 + 5. int num = 12345; int sum = 0; /* missing loop header */ { sum += num % 10; num /= 10; } System.out.println(sum); Which of the following should replace /* missing loop header */ so that the code segment will work as intended?

while (num > 0)

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?

In line 18, change else if to if.

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?

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

Consider the following code segment. String word = "computer"; int num = 3; String result = ""; for (int k = num; k >= 0; k--) { result += word.substring(0, k); } System.out.print(result); What is printed as a result of executing the code segment?

comcoc

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?

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

The following class is used to represent shipping containers. Each container can hold a number of units equal to unitsPerContainer. public class UnitsHandler { private static int totalUnits = 0; private static int containers = 0; private static int unitsPerContainer = 0; public UnitsHandler(int containerSize) { unitsPerContainer = containerSize; } public static void update(int c) { containers = c; totalUnits = unitsPerContainer * containers; } } The following code segment appears in a method in a class other than UnitsHandler. Assume that no other code segments have created or modified UnitsHandler objects. UnitsHandler large = new UnitsHandler(100); UnitsHandler.update(8);

The code segment creates a UnitsHandler object called large and sets the static variables unitsPerContainer, containers, and totalUnits to 100, 8, and 800, respectively.

Consider the following class declaration. public class Student { private String firstName; private String lastName; private int age; public Student(String firstName, String lastName, int age) { firstName = firstName; lastName = lastName; age = age; } public String toString() { return firstName + " " + lastName; } } The following code segment appears in a method in a class other than Student. It is intended to create a Student object and then to print the first name and last name associated with that object. Student s = new Student("Priya", "Banerjee", -1); System.out.println(s); Which of the following best explains why the code segment does not work as expected?

The code segment will compile, but the instance variables will not be initialized correctly because the variable names firstName, lastName, and age refer to the local variables inside the constructor.

Consider the following class definition. public class Time { private int hours; private int minutes; public Time(int h, int m) { hours = h; minutes = m; } /** Returns true if hours * 60 + minutes of this * object is equal to hours * 60 + minutes of object * other; otherwise returns false */ public boolean equals(Object other) { //implementation not shown } } 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);

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?

The variable tree1 is assigned a reference to a new DeciduousTree object created using the DeciduousTree constructor, which uses super to set tree1's treeVariety attribute to "Oak". The variable tree2 is assigned a reference to a new EvergreenTree object created using the EvergreenTree constructor, which uses super to set tree2's treeVariety attribute to "Fir".

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?

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

Consider the following code segment. int[] arr = {10, 20, 30, 40, 50}; for(int x = 1; x < arr.length - 1; x++) { arr[x + 1] = arr[x] + arr[x + 1]; } Which of the following represents the contents of arr after the code segment has been executed?

{10, 20, 50, 90, 140}

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 and II only

Consider the following class definition. public class BoolTest { private int one; public BoolTest(int newOne) { one = newOne; } public int getOne() { return one; } public boolean isGreater(BoolTest other) { /* missing code */ } } The isGreater method is intended to return true if the value of one for this BoolTest object is greater than the value of one for the BoolTest parameter other, and false otherwise. The following code segments have been proposed to replace /* missing code */. return one > other.one; return one > other.getOne(); return getOne() > other.one; Which of the following replacements for /* missing code */ can be used so that isGreater will work as intended?

I, II and III

Consider the following code segment. int[] arr = {1, 2, 3, 4, 5}; Which of the following code segments would correctly set the first two elements of array arr to 10 so that the new value of array arr will be {10, 10, 3, 4, 5} ?

arr[0] = 10; arr[1] = 10;

Consider the following class declaration. The changeWeather method is intended to update the value of the instance variable weather and return the previous value of weather before it was updated. public class WeatherInfo { private String city; private int day; private String weather; public WeatherInfo(String c, int d, String w) { city = c; day = d; weather = w; } public String changeWeather(String w) { /* missing code */ } } Which of the following options should replace /* missing code */ so that the changeWeather method will work as intended?

String prev = weather; weather = w; return prev;

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?

The Poodle variable myDog is a reference to an instantiated Poodle object. 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 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?

The accessor method is missing a return type.

Consider the following method, which is intended to return the index of the first negative integer in a given array of integers. public int positionOfFirstNegative(int[] values) { int index = 0; while (values[index] >= 0) { index++; } return index; } What precondition is needed on the values array so that the method will work as intended?

The array values must contain at least one negative integer.

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); } } public 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?

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

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" ? When alice references an object of type Person When alice references an object of type EvilPerson When alice references an object of type Henchman

II and III only

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?

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

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? When the variable someBird has been declared as type Duck When the variable someBird has been declared as type Chicken When the variable someBird has been declared as type Rooster

I, II, and III

Consider the following class definition. public class Toy { private int yearFirstSold; public int getYearFirstSold() { return yearFirstSold; } /* There may be instance variables, constructors, and other methods not shown. */ } The following code segment, which appears in a class other than Toy, prints the year each Toy object in toyArray was first sold by its manufacturer. Assume that toyArray is a properly declared and initialized array of Toy objects. for (Toy k : toyArray) { System.out.println(k.getYearFirstSold()); } Which of the following could be used in place of the given code segment to produce the same output? I. for (int k = 0; k < toyArray.length; k++) { System.out.println(getYearFirstSold(k)); } II. for (int k = 0; k < toyArray.length; k++) { System.out.println(k.getYearFirstSold()); } III. for (int k = 0; k < toyArray.length; k++) { System.out.println(toyArray[k].getYearFirstSold()); }

III only

Consider the following class, which models a bank account. The deposit method is intended to update the account balance by a given amount; however, it does not work as intended. public class BankAccount { private String accountOwnerName; private double balance; private int accountNumber; public BankAccount(String name, double initialBalance, int acctNum) { accountOwnerName = name; balance = initialBalance; accountNumber = acctNum; } public void deposit(double amount) { double balance = balance + amount; } } What is the best explanation of why the deposit method does not work as intended?

In the deposit method, the variable balance is declared as a local variable and is different from the instance variable balance.

The Fibonacci numbers are a sequence of integers. The first two numbers are 1 and 1. Each subsequent number is equal to the sum of the previous two integers. For example, the first seven Fibonacci numbers are 1, 1, 2, 3, 5, 8, and 13. The following code segment is intended to fill the fibs array with the first ten Fibonacci numbers. The code segment does not work as intended. int[] fibs = new int[10]; fibs[0] = 1; fibs[1] = 1; for (int j = 1; j < fibs.length; j++) { fibs[j] = fibs[j - 2] + fibs[j - 1]; } Which of the following best identifies why the code segment does not work as intended?

In the for loop header, the initial value of j should be 2.

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?

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

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?

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

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?

Line 8 causes a compile-time error because the parameter a1 in the call displayFeatures(a1) has been declared as an Appliance.

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, int 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 will display Number of Wheels: 4 Max Speed: Fast when executed in a class other than Vehicle or Motorizeddog?

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

Consider the following code segment. int[] numbers = {1, 2, 3, 4, 5, 6}; for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } Which of the following for loops produces the same output as the code segment?

for (int x : numbers) { System.out.println(x); }


Kaugnay na mga set ng pag-aaral

Hazard Communication Program - PP

View Set

Evidence Based Practice - Quiz questions

View Set

Chapter 30: Assessment and Management of Patients With Vascular Disorders and Problems of Peripheral Circulation

View Set

Chapter 5 - Transfer of Title to Real Property

View Set

Project management final exam prep

View Set

California: Real Estate Principles - Chapter 1

View Set

Chapter 6_NEW! Mini Sim_B2B MARK3300

View Set

Mean, Median, Mode, and Confidence Intervals Sensitivity, specificity, and Predictive Value Standard Curves

View Set