APCSA ALL FINAL

0.0(0)
studied byStudied by 16 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/439

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

440 Terms

1
New cards
Consider the following method.
public double puzzle(int x)
{
Double y \= x / 2.0;
y /\= 2;

return y.doubleValue();
}
Assume that the method call puzzle(3) appears in a method in the same class as puzzle. What value is returned as a result of the method call?
A 0.0
B 0.5
C 0.75
D 1.0
E 1.5
C 0.75
2
New cards
Consider the following code segment, which is intended to assign to num a random integer value between min and max, inclusive. Assume that min and max are integer variables and that the value of max is greater than the value of min.
double rn \= Math.random();
int num \= /* missing code */;
Which of the following could be used to replace /* missing code */ so that the code segment works as intended?
A (int) (rn * max) + min
B (int) (rn * max) + min - 1
C (int) (rn * (max - min)) + min
D (int) (rn * (max - min)) + 1
E (int) (rn * (max - min + 1)) + min
E (int) (rn * (max - min + 1)) + min
3
New cards
Consider the following method.
public void doSomething()
{
System.out.println("Something has been done");
}
Each of the following statements appears in a method in the same class as doSomething. Which of the following statements are valid uses of the method doSomething ?
doSomething();
String output \= doSomething();
System.out.println(doSomething());
A I only
B II only
C I and II only
D I and III only
E I, II, and III
A I only
4
New cards
Which of the following statements assigns a random integer between 1 and 10, inclusive, to rn ?
A int rn \= (int) (Math.random()) * 10;
B int rn \= (int) (Math.random()) * 10 + 1;
C int rn \= (int) (Math.random() * 10);
D int rn \= (int) (Math.random() * 10) + 1;
E int rn \= (int) (Math.random() + 1) * 10;
D int rn \= (int) (Math.random() * 10) + 1;
5
New cards
Consider the following class declaration.
public class GameClass
{
private int numPlayers;
private boolean gameOver;

public Game()
{
numPlayers \= 1;
gameOver \= false;
}

public void addPlayer()
{
numPlayers++;
}

public void endGame()
{
gameOver \= true;
}
}
Assume that the GameClass object game has been properly declared and initialized in a method in a class other than GameClass. Which of the following statements are valid?
game.numPlayers++;
game.addPlayer();
game.gameOver();
game.endGame();
A IV only
B I and III only
C I and IV only
D II and IV only
E II, III, and IV only
D II and IV only
6
New cards
Consider the following class declaration.

Which of the following declarations will compile without error?
Student a \= new Student();
Student b \= new Student("Juan", 15);
Student c \= new Student("Juan", "15");
A I only
B II only
C I and II only
D I and III only
E I, II, and III
C I and II only
7
New cards
Consider the following class definition.
public class ExamScore
{
private String studentId;
private double score;

public ExamScore(String sid, double s)
{
studentId \= sid;
score \= s;
}

public double getScore()
{
return score;
}

public void bonus(int b)
{
score +\= score * b/100.0;
}
}
Assume that the following code segment appears in a class other than ExamScore.
ExamScore es \= new ExamScore("12345", 80.0);
es.bonus(5);
System.out.println(es.getScore());
What is printed as a result of executing the code segment?
A 4.0
B 5.0
C 80.0
D 84.0
E 85.0
D 84.0
8
New cards
Consider the following code segment.
String str \= "CompSci";
System.out.println(str.substring(0, 3));
int num \= str.length();
What is the value of num when the code segment is executed?
A 3
B 4
C 5
D 6
E 7
E 7
9
New cards
Consider the following method.
public int timesTwo (int n)
{
return n * 2;
}
The following code segment appears in a method in the same class as the timesTwo method.
Integer val \= 10;
int result1 \= timesTwo(val);
Integer result2 \= result1;
System.out.print(result2);
What, if anything, is printed as a result of executing the code segment?
A 10
B 20
C Nothing; the code segment will not compile because timesTwo cannot accept an Integer parameter.
D Nothing; the code segment will not compile because the value returned by timesTwo cannot be assigned to result1.
E Nothing; the code segment will not compile because the int variable result1 cannot be assigned to the Integer variable result2.
B 20
10
New cards
Assume that myList is an ArrayList that has been correctly constructed and populated with objects. Which of the following expressions produces a valid random index for myList?
A (int) ( Math.random () * myList.size () ) - 1
B (int) ( Math.random () * myList.size () )
C (int) ( Math.random () * myList.size () ) + 1
D (int) ( Math.random () * (myList.size () + 1) )
E Math.random (myList.size () )
B (int) ( Math.random () * myList.size () )
11
New cards
Consider the following code segment.
String str \= "0";
str +\= str + 0 + 8;
System.out.println(str);
What is printed as a result of executing the code segment?
A 8
B 08
C 008
D 0008
E Nothing is printed, because numerical values cannot be added to a String object.
D 0008
12
New cards
The Student class has been defined to store and manipulate grades for an individual student. The following methods have been defined for the class.
/* Returns the sum of all of the student's grades */
public double sumOfGrades()
{ /* implementation not shown */ }

/* Returns the total number of grades the student has received */
public int numberOfGrades()
{ /* implementation not shown */ }

/* Returns the lowest grade the student has received */
public double lowestGrade()
{ /* implementation not shown */ }
Which of the following statements, if located in a method in the Student class, will determine the average of all of the student's grades except for the lowest grade and store the result in the double variable newAverage ?
A newAverage \= sumOfGrades() / numberOfGrades() - 1;
B newAverage \= sumOfGrades() / (numberOfGrades() - 1);
C newAverage \= sumOfGrades() - lowestGrade() / (numberOfGrades() - 1);
D newAverage \= (sumOfGrades() - lowestGrade()) / numberOfGrades() - 1;
E newAverage \= (sumOfGrades() - lowestGrade()) / (numberOfGrades() - 1);
E newAverage \= (sumOfGrades() - lowestGrade()) / (numberOfGrades() - 1);
13
New cards
Consider the following method.

What value is returned as a result of the call scramble("compiler", 3)?
A "compiler"
B "pilercom"
C "ilercom"
D "ilercomp"
E No value is returned because an IndexOutOfBoundsException will be thrown.
C "ilercom"
14
New cards
Directions: Select the choice that best fits each statement. The following question(s) refer to the following information.
Consider the following partial class declaration.

The following declaration appears in another class.SomeClass obj \= new SomeClass ( );Which of the following code segments will compile without error?
A int x \= obj.getA ( );
B int x;
obj.getA (x);
C int x \= obj.myA;
D int x \= SomeClass.getA ( );
E int x \= getA(obj);
A int x \= obj.getA ( );
15
New cards
Consider the code segment below.
int a \= 1988;
int b \= 1990;

String claim \= " that the world's athletes " +
"competed in Olympic Games in ";

String s \= "It is " + true + claim + a +
" but " + false + claim + b + ".";

System.out.println(s);
What, if anything, is printed when the code segment is executed?
A It is trueclaima but falseclaimb.
B It is trueclaim1998 but falseclaim1990.
C It is true that the world's athletes competed in Olympic Games in a but false that the world's athletes competed in Olympic Games in b.
D It is true that the world's athletes competed in Olympic Games in 1988 but false that the world's athletes competed in Olympic Games in 1990.
E Nothing is printed because the code segment does not compile.
D It is true that the world's athletes competed in Olympic Games in 1988 but false that the world's athletes competed in Olympic Games in 1990.
16
New cards
Consider the following code segment.
String temp \= "comp";
System.out.print(temp.substring(0) + " " +
temp.substring(1) + " " +
temp.substring(2) + " " +
temp.substring(3));
What is printed when the code segment is executed?
A comp
B c o m p
C comp com co c
D comp omp mp p
E comp comp comp comp
D comp omp mp p
17
New cards
Consider the following code segment.
int one \= 1;
int two \= 2;
String zee \= "Z";
System.out.println(one + two + zee);
What is printed as a result of executing the code segment?
A 12Z
B 3Z
C 12zee
D 3zee
E onetwozee
B 3Z
18
New cards
Consider the following Point2D class.
public class Point2D
{
private double xCoord;
private double yCoord;

public Point2D(double x, double y)
{
xCoord \= x;
yCoord \= y;
}
}
Which of the following code segments, appearing in a class other than Point2D, will correctly create an instance of a Point2D object?
A Point2D p \= (3.0, 4.0);
B Point2D p \= Point2D(3.0, 4.0);
C new p \= Point2D(3.0, 4.0);
D new Point2D \= p(3.0, 4.0);
E Point2D p \= new Point2D(3.0, 4.0);
E Point2D p \= new Point2D(3.0, 4.0);
19
New cards
Consider the following Book and AudioBook classes.

Consider the following code segment that appears in a class other than Book or AudioBook.

Which of the following best explains why the code segment will not compile?
A Line 2 will not compile because variables of type Book may not refer to variables of type AudioBook.
B Line 4 will not compile because variables of type Book may only call methods in the Book class.
C Line 5 will not compile because the AudioBook class does not have a method named toString declared or implemented.
D Line 6 will not compile because the statement is ambiguous. The compiler cannot determine which length method should be called.
E Line 7 will not compile because the element at index 1 in the array named books may not have been initialized.
B Line 4 will not compile because variables of type Book may only call methods in the Book class.
20
New cards
Consider the following methods, which appear in the same class.
public int function1(int i, int j)
{
return i + j;
}

public int function2(int i, int j)
{
return j - i;
}
Which of the following statements, if located in a method in the same class, will initialize the variable x to 11?
A int x \= function2(4, 5) + function1(1, 3);
B int x \= function1(4, 5) + function2(1, 3);
C int x \= function1(4, 5) + function2(3, 1);
D int x \= function1(3, 1) + function2(4, 5);
E int x \= function2(3, 1) + function1(4, 5);
B int x \= function1(4, 5) + function2(1, 3);
21
New cards
Consider the following method, which is intended to return true if at least one of the three strings s1, s2, or s3 contains the substring "art". Otherwise, the method should return false.

Which of the following method calls demonstrates that the method does not work as intended?
A containsArt ("rattrap", "similar", "today")
B containsArt ("start", "article", "Bart")
C containsArt ("harm", "chortle", "crowbar")
D containsArt ("matriculate", "carat", "arbitrary")
E containsArt ("darkroom", "cartoon", "articulate")
A containsArt ("rattrap", "similar", "today")
22
New cards
Consider the following class.

public class SomeMethods
{public void one(int first)
{ / * implementation not shown * / }
public void one(int first, int second)
{ / * implementation not shown * / }
public void one(int first, String second)
{ / * implementation not shown * / }
}

Which of the following methods can be added to the SomeMethods class without causing a compile-time error?
public void one(int value){ / * implementation not shown * / }
public void one (String first, int second)
{ / * implementation not shown * / }
public void one (int first, int second, int third)
{ / * implementation not shown * / }
A I only
B I and II only
C I and III only
D II and III only
E I, II, and III
D II and III only
23
New cards
A student has created an OrderedPair class to represent points on an xy-plane. The class contains the following.
An int variable called x to represent an x-coordinate.
An int variable called y to represent a y-coordinate.
A method called printXY that will print the values of x and y.
The object origin will be declared as type OrderedPair.
Which of the following descriptions is accurate?
A origin is an instance of the printXY method.
B origin is an instance of the OrderedPair class.
C origin is an instance of two int objects.
D OrderedPair is an instance of the origin object.
E printXY is an instance of the OrderedPair class.
B origin is an instance of the OrderedPair class.
24
New cards
A student has created a Song class. The class contains the following variables.
A String variable called artist to represent the artist name
A String variable called title to represent the song title
A String variable called album to represent the album title
The object happyBirthday will be declared as type Song.
Which of the following statements is true?
A artist, title, and album are instances of the Song class.
B happyBirthday is an instance of three String objects.
C happyBirthday is an instance of the Song class.
D Song is an instance of the happyBirthday object.
E Song is an instance of three String objects.
C happyBirthday is an instance of the Song class.
25
New cards
Consider the following method that is intended to determine if the double values d1 and d2 are close enough to be considered equal. For example, given a tolerance of 0.001, the values 54.32271 and 54.32294 would be considered equal.

Which of the following should replace / * missing code * / so that almostEqual will work as intended?
A return (d1 - d2)
E return Math.abs(d1 - d2)
26
New cards
A pair of number cubes is used in a game of chance. Each number cube has six sides, numbered from 1 to 6, inclusive, and there is an equal probability for each of the numbers to appear on the top side (indicating the cube's value) when the number cube is rolled. The following incomplete statement appears in a program that computes the sum of the values produced by rolling two number cubes.
int sum \= / * missing code * / ;
Which of the following replacements for /* missing code */ would best simulate the value produced as a result of rolling two number cubes?
A 2 * (int) (Math.random() * 6)
B 2 * (int) (Math.random() * 7)
C (int) (Math.random() * 6) + (int) (Math.random() * 6)
D (int) (Math.random() * 13)
E 2 + (int) (Math.random() * 6) + (int) (Math.random() * 6)
E 2 + (int) (Math.random() * 6) + (int) (Math.random() * 6)
27
New cards
Consider the following code segment.
String oldStr \= "ABCDEF";
String newStr \= oldStr.substring(1, 3) + oldStr.substring(4);
System.out.println(newStr);
What is printed as a result of executing the code segment?
A ABCD
B BCDE
C BCEF
D BCDEF
E ABCDEF
C BCEF
28
New cards
Consider the following class definition.
public class Thing
{
public void talk()
{
System.out.print("Hello ");
}

public void name()
{
System.out.print("my friend");
}

public void greet()
{
talk();
name();
}

/* Constructors not shown */
}
Which of the following code segments, if located in a method in a class other than Thing, will cause the message "Hello my friend" to be printed?
A Thing a \= new Thing();Thing.talk();Thing.name();
B Thing a \= new Thing();Thing.greet();
C Thing a \= new Thing();a.talk();
D Thing a \= new Thing();a.greet();
E Thing a \= new Thing();a.name();a.talk();
D Thing a \= new Thing();a.greet();
29
New cards
A student has created a Car class. The class contains variables to represent the following.
A String variable called color to represent the color of the car
An int variable called year to represent the year the car was made
A String variable called make to represent the manufacturer of the car
A String variable called model to represent the model of the car
The object vehicle will be declared as type Car.
Which of the following descriptions is accurate?
A An instance of the vehicle class is Car.
B An instance of the Car object is vehicle.
C An attribute of the year object is int.
D An attribute of the vehicle object is color.
E An attribute of the Car instance is vehicle.
D An attribute of the vehicle object is color.
30
New cards
Consider the following class definition.
public class Student
{
private int studentID;
private int gradeLevel;
private boolean honorRoll;

public Student(int s, int g)
{
studentID \= s;
gradeLevel \= g;
honorRoll \= false;
}

public Student(int s)
{
studentID \= s;
gradeLevel \= 9;
honorRoll \= false;
}
}
Which of the following code segments would successfully create a new Student object?
Student one \= new Student(328564, 11);
Student two \= new Student(238783);
int id \= 392349;int grade \= 11;Student three \= new Student(id, grade);
A I only
B II only
C III only
D I and II only
E I, II, and III
E I, II, and III
31
New cards
Consider the following class declaration.

Assume that the following declaration has been made.Person student \= new Person ("Thomas", 1995);Which of the following statements is the most appropriate for changing the name of student from "Thomas" to "Tom" ?
A student \= new Person ("Tom", 1995);
B student.myName \= "Tom";
C student.getName ("Tom");
D student.setName ("Tom");
E Person.setName ("Tom");
D student.setName ("Tom");
32
New cards
Consider the following class.
public class WindTurbine
{
private double efficiencyRating;

public WindTurbine()
{
efficiencyRating \= 0.0;
}

public WindTurbine(double e)
{
efficiencyRating \= e;
}
}

Which of the following code segments, when placed in a method in a class other than WindTurbine, will construct a WindTurbine object wt with an efficiencyRating of 0.25 ?
A WindTurbine wt \= new WindTurbine(0.25);
B WindTurbine wt \= 0.25;
C WindTurbine wt \= new WindTurbine();wt \= 0.25;
D WindTurbine wt \= new WindTurbine();wt.efficiencyRating \= 0.25;
E new WindTurbine wt \= 0.25;
A WindTurbine wt \= new WindTurbine(0.25);
33
New cards
Consider the following method.
public double myMethod(int a, boolean b)
{ /* implementation not shown */ }
Which of the following lines of code, if located in a method in the same class as myMethod, will compile without error?
A int result \= myMethod(2, false);
B int result \= myMethod(2.5, true);
C double result \= myMethod(0, false);
D double result \= myMethod(true, 10);
E double result \= myMethod(2.5, true);
C double result \= myMethod(0, false);
34
New cards
Consider the following code segment.
double d1 \= 10.0;
Double d2 \= 20.0;
Double d3 \= new Double(30.0);
double d4 \= new Double(40.0);

System.out.println(d1 + d2 + d3.doubleValue() + d4);
What, if anything, is printed when the code segment is executed?
A 100.0
B 10.050.040.0
C 10.020.070.0
D 10.020.030.040.0
E There is no output due to a compilation error.
A 100.0
35
New cards
Consider the following methods, which appear in the same class.
public void printSum(int x, double y)
{
System.out.println(x + y);
}

public void printProduct(double x, int y)
{
System.out.println(x * y);
}
Consider the following code segment, which appears in a method in the same class as printSum and printProduct.
int num1 \= 5;
double num2 \= 10.0;
printSum(num1, num2);
printProduct(num1, num2);
What, if anything, is printed as a result of executing the code segment?
A 15
50
B 15
50.0
C 15.0
50
D 15.0
50.0
E Nothing is printed because the code does not compile.
E Nothing is printed because the code does not compile.
36
New cards
Consider the following method.

public int addFun(int n)
{
if (n
C
16
37
New cards
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?
A
1
B
2
C
3
D
4
E
5
B
2
38
New cards
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
C
6
39
New cards
Consider the following method.
public static int calcMethod(int num)
{
if (num \== 0)
{
return 10;
}
return num + calcMethod(num / 2);
}
What value is returned by the method call calcMethod(16) ?
A
10
B
26
C
31
D
38
E
41
E
41
40
New cards
Consider the following two static methods, where f2 is intended to be the iterative version of f1.
public static int f1(int n)
{
if (n < 0)
{
return 0;
}
else
{
return (f1(n - 1) + n * 10);
}
}
public static int f2(int n)
{
int answer \= 0;
while (n \> 0)
{
answer \= answer + n * 10;
n--;
}

return answer;
}

The method f2 will always produce the same results as f1 under which of the following conditions?
I. n < 0
II. n \= 0
III. n \> 0
A
I only
B
II only
C
III only
D
II and III only
E
I, II, and III
E
I, II, and III
41
New cards
Consider the following method.
public String goAgain(String str, int index)
{
if (index \>\= str.length())
return str;

return str + goAgain(str.substring(index), index + 1);
}

What is printed as a result of executing the following statement?
System.out.println(goAgain("today", 1));
A
today
B
todayto
C
todayoday
D
todayodayay
E
todayodaydayayy
D
todayodayay
42
New cards
Directions: Select the choice that best fits each statement. The following question(s) refer to the following information
Consider the following binarySearch method. The method correctly performs a binary search.

Consider the following code segment.
int [ ] values \= {1, 2, 3, 4, 5, 8, 8, 8};int target \= 8;
What value is returned by the call binarySearch (values, target) ?
A
-1
B
3
C
5
D
6
E
8
C
5
43
New cards
Consider the following mergeSortHelper method, which is part of an algorithm to recursively sort an array of integers.
/\** Precondition: (arr.length \== 0 or 0
D
{30, 50, 80} and {20, 60, 70} are merged to form {20, 30, 50, 60, 70, 80}.
44
New cards
Consider the following data field and method. Method maxHelper is intended to return the largest value among the first numVals values in an array; however, maxHelper does not work as intended.
private int[] nums;

// precondition: 0 < numVals
E
Method maxHelper never works as intended.
45
New cards
The following question refer to the following information.
Consider the following data field and method. Method maxHelper is intended to return the largest value among the first numVals values in an array; however, maxHelper does not work as intended.
private int[] nums;

// precondition: 0 < numVals
B
Insert the following statement before Line 1.
if (numVals \== 1
return nums[0];
46
New cards
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?
A
1
B
3
C
4
D
5
E
7
C
4
47
New cards
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
C
int val \= maximum(data, start + 1);
48
New cards
Consider the following method.
public static int mystery(int n)
{
if (n
E
25
49
New cards
Consider the following method.

Which of the following best describes what the call mystery(numbers, val, numbers.length)does? You may assume that variables numbers and val have been declared and initialized.
A
Returns 1 if the last element in numbers is equal to val; otherwise, returns 0
B
Returns the index of the last element in numbers that is equal to val
C
Returns the number of elements in numbers that are equal to val
D
Returns the number of elements in numbers that are not equal to val
E
Returns the maximum number of adjacent elements that are not equal to val
C
Returns the number of elements in numbers that are equal to val
50
New cards
Consider the following data field and method.
private int[][] mat;
public int mystery(int r, int c)
{
if (r !\= 0 || c !\= 0)
{
return (mat[r][c] + mystery(r - 1, c - 1));
}
else
{
return mat[r][c];
}
}
Assume that mat is the 2-D array shown below.
012300123145672891011312131415

What value is returned as a result of the call mystery(2, 3)?
A
1
B
11
C
17
D
18
E
No value is returned because mystery throws an ArrayIndexOutOfBoundsException.
E
No value is returned because mystery throws an ArrayIndexOutOfBoundsException.
51
New cards
Consider the following method.
// precondition: arr contains no duplicates;
// the elements in arr are in sorted order;
// 0 ≤ low ≤ arr.length; low - 1 ≤ high < arr.length
public static int mystery(int[] arr, int low, int high, int num)
{
int mid \= (low + high) / 2;

if (low \> high)
{
return low;
}
else if (arr[mid] < num)
{
return mystery(arr, mid + 1, high, num);
}
else if (arr[mid] \> num)
{
return mystery(arr, low, mid - 1, num);
}
else // arr{mid] \== num
{
return mid;
}
}
How many calls to mystery (including the initial call) are made as a result of the call mystery(arr, 0, arr.length - 1, 14) if arr is the following array?

A
1
B
2
C
4
D
7
E
8
C
4
52
New cards
Consider the following instance variable and method.

What is returned by the call mystery (0, arr.length − 1, num) ?
A
The number of elements in arr that are less than num
B
The number of elements in arr that are less than or equal to num
C
The number of elements in arr that are equal to num
D
The number of elements in arr that are greater than num
E
The index of the middle element in arr
A
The number of elements in arr that are less than num
53
New cards
Consider the following recursive method.

Assuming that k is a nonnegative integer and m \= 2k, what value is returned as a result of the call mystery (m) ?
A
0
B
k
C
m
D
E
B
k
54
New cards
// precondition: x \>\= 0
public void mystery(int x)
{
if ((x / 10) !\= 0)
{
mystery(x / 10);
}

System.out.print(x % 10);
}

Which of the following is printed as a result of the call mystery(123456) ?
A
16
B
56
C
123456
D
654321
E
Many digits are printed due to infinite recursion.
C
123456
55
New cards
Consider the following method.

Which of the following is printed as a result of the call mystery (1234)?
A
1234
B
4321
C
12344321
D
43211234
E
Many digits are printed due to infinite recursion.
D
43211234
56
New cards
Consider the following mergeSortHelper method, which is part of an algorithm to recursively sort an array of integers.
/\** Precondition: (arr.length \== 0 or 0
C
3
57
New cards
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?
A
1
B
2
C
3
D
4
E
5
B
2
58
New cards
Consider the following method.
public static void mystery(int[] a, int index)
{
if (index < a.length)
{
mystery(a, index + 1);
}
if (index \> 0)
{
System.out.print(a[index - 1]);
}
}
What is printed as a result of executing the following code segment?
int[] array \= {6, 8, 7, 9, 5};
mystery(array, 0);
A
5978
B
8795
C
59786
D
68795
E
Many digits are printed because of infinite recursion.
C
59786
59
New cards
Consider the following recursive method.
public static void stars(int num)
{
if (num \== 1)
{
return;
}

stars(num - 1);

for (int i \= 0; i < num; i++)
{
System.out.print("*");
}
System.out.println();
}
What is printed as a result of the method call stars(5) ?
A
\*****
B
**
\***
\****
\*****
C
*
**
\***
\****
\*****
D
\*****
\****
\***
**
E
\*****
\****
\***
**
*
B
**
\***
\****
\*****
60
New cards
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
C
words.remove(words.size() - 1);
printRightToLeft(words);
61
New cards
Consider the following method.

public String recScramble(String str, int[] positions, int k)
{
if (str \== null || str.length() \== 0)
return "";
if (str.length() \== 1)
return str;
int pos \= positions[k];
String nStr \= str.substring(pos, pos + 1);
str \= str.substring(0, pos) + str.substring(pos + 1);
return nStr + recScramble(str, positions, k + 1);
}

Consider the following code segment.
int[] indexes \= {2, 1, 1};
System.out.println(recScramble("epic", indexes, 0));

What is printed as a result of executing the code segment?
A
cepi
B
epci
C
iecp
D
iepc
E
ipce
E
ipce
62
New cards
Consider the following static method.
private static void recur(int n)
{
if (n !\= 0)
{
recur(n - 2);
System.out.print(n + " ");
}
}
What numbers will be printed as a result of the call recur(7) ?
A
-1 1 3 5 7
B
1 3 5 7
C
7 5 3 1
D
Many numbers will be printed because of infinite recursion.
E
No numbers will be printed because of infinite recursion.
E
No numbers will be printed because of infinite recursion.
63
New cards
Consider the following recursive method.
What value is returned as a result of the call recur(27)?
A
8
B
9
C
12
D
16
E
18
D
16
64
New cards
Consider the following recursive method.
public static String recur(int val)
{
String dig \= "" + (val % 3);

if (val / 3 \> 0)
return dig + recur(val / 3);

return dig;
}

What is printed as a result of executing the following statement?
System.out.println(recur(32));
A
20
B
102
C
210
D
1020
E
2101
E
2101
65
New cards
Consider the following recursive method.
private int recur(int n)
{
if (n
D
5
66
New cards
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?
A
bark(num - 5);
B
bark(num - 1);
C
bark(num);
D
bark(num + 1);
E
bark(num + 5);
B
bark(num - 1);
67
New cards
Consider the following two methods, which are intended to return the same values when they are called with the same positive integer parameter n.
public static int mystery1(int n)
{
if (n \> 1)
{
return 5 + mystery1(n - 1);
}
else
{
return 1;
}
}
public static int mystery2(int n)
{
int total \= 0;
int x \= 1;
while (x < n)
{
total +\= 5;
x++;
}
return total;
}
Which, if any, of the following changes to mystery2 is required so that the two methods work as intended?
A
The variable total should be initialized to 1.
B
The variable x should be initialized to 0.
C
The condition in the while loop header should be x < n - 1.
D
The condition in the while loop header should be x
A
The variable total should be initialized to 1.
68
New cards
Consider the following method.
/* Precondition: j
D
It prints the integers from j to k, inclusive, in order from least to greatest.
69
New cards
Consider the following recursive method.
/\** Precondition: 0
C
The number of times that v occurs in nums is returned.
70
New cards
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?
A
It prints the first character of str.
B
It prints the last character of str.
C
It prints the characters of str in the order they appear.
D
It prints the characters of str in reverse order.
E
It prints nothing due to infinite recursion.
D
It prints the characters of str in reverse order.
71
New cards
Consider the following recursive method.
public static boolean recurMethod(String str)
{
if (str.length()
D
recurMethod("edcba")
72
New cards
Consider the following method.
public static int mystery(ArrayList
C
It returns the sum of the elements in numList.
73
New cards
Directions: Select the choice that best fits each statement. The following question(s) refer to the following information
Consider the following instance variable and methods. You may assume that data has been initialized with length \> 0. The methods are intended to return the index of an array element equal to target, or -1 if no such element exists.

For which of the following test cases will the call seqSearchRec(5) always result in an error?
data contains only one element.
data does not contain the value 5.
data contains the value 5 multiple times.
A
I only
B
II only
C
III only
D
I and II only
E
I, II, and III
B
II only
74
New cards
Consider the following method.

What will be printed as a result of the call showMe(0) ?
A
10
B
11
C
0 1 2 3 4 5 6 7 8 9
D
9 8 7 6 5 4 3 2 1 0
E
0 1 2 3 4 5 6 7 8 9 10
A
10
75
New cards
Consider the following method.
// Precondition: b \> 0
public int surprise(int b)
{
if ((b % 2) \== 0)
{
if (b < 10)
return b;
else
return ((b % 10) + surprise(b / 10));
}
else
{
if (b < 10)
return 0;
else
return surprise(b / 10);
}
}
Which of the following expressions will evaluate to true ?
surprise(146781) \== 0
surprise(7754) \== 4
surprise(58216) \== 16
A
I only
B
II only
C
III only
D
II and III only
E
I, II, and III
D
II and III only
76
New cards
Consider the following recursive method.

Assume that int val has been declared and initialized with a value that satisfies the precondition of the method. Which of the following best describes the value returned by the call what(val) ?
A
The number of digits in the decimal representation of val is returned.
B
The sum of the digits in the decimal representation of val is returned.
C
Nothing is returned. A run-time error occurs because of infinite recursion.
D
The value 1 is returned.
E
The value val/10 is returned.
A
The number of digits in the decimal representation of val is returned.
77
New cards
Consider the following recursive method.

What is printed as a result of the call whatsItDo ("WATCH") ?
A
WATC
WAT
WA
W
B
WATCH
WATC
WAT
WA
C
W
WA
WAT
WATC
D
W
WA
WAT
WATC
WATCH
E
WATCH
WATC
WAT
WA
W
WA
WAT
WATC
WATCH
C
W
WA
WAT
WATC
78
New cards
Consider the following recursive method.

What is printed as a result of the call whatsItDo("WATCH") ?
A
H
B
WATC
C
ATCH
ATC
AT
A
D
WATC
WAT
WA
W
E
WATCH
WATC
WAT
WA
D
WATC
WAT
WA
W
79
New cards
Directions: Select the choice that best fits each statement. The following question(s) refer to the following information
Consider the following binarySearch method. The method correctly performs a binary search.

Suppose the binarySearch method is called with an array containing 2,000 elements sorted in increasing order. What is the maximum number of times that the statement indicated by / * Calculate midpoint * / could execute?
A
2,000
B
1,000
C
20
D
11
E
1
D
11
80
New cards
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.
B
An implicit call to the one-parameter Bike constructor with the parameter passed to the EBike constructor initializes the instance variable numWheels. The instance variable numBatteries is initialized using the value of the parameter batteries.
C
Because super is not explicitly called from the EBike constructor, the instance variable numWheels is not initialized. The instance variable numBatteries is initialized using the value of the parameter batteries.
D
The code segment will not execute because the Bike class is a superclass and must have a constructor.
E
The code segment will not execute because the constructor of the EBike class is missing a second parameter to use to initialize the numWheels instance variable.
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.
81
New cards
Consider the following class definitions.
public class Bird
{
private int beakStrength;

public 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?
A
The Bird variable b is instantiated as a Hawk. The instance variable talonStrength is initialized with the value from the parameter talon. The Hawk constructor cannot set the instance variable beakStrength because a subclass does not have access to a private variable in its superclass.
B
The Bird variable b is instantiated as a Hawk. The call super(beak) returns a value from the instance variable beakStrength in the superclass and makes it accessible in the subclass. The instance variable talonStrength is then initialized with the value from the parameter talon.
C
The Bird variable b is instantiated as a Hawk. The instance variable talonStrength is initialized with the value from the parameter talon. No other initializations are made to any instance variables.
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.
E
The code segment will not execute because the Bird variable b cannot be instantiated as a Hawk.
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.
82
New cards
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?
A
The TextBook constructor initializes the instance variable subject with the value of the parameter theSubject, and then invokes the zero-parameter Book constructor, which initializes the instance variable bookTitle to "".
B
The TextBook constructor initializes the instance variable subject with the value of the parameter theSubject, and then invokes the one-parameter Book constructor with theSubject as the parameter, which initializes the instance variable bookTitle to the value of the parameter theSubject.
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.
D
The code segment will not execute because the TextBook constructor does not contain an explicit call to one of the Book constructors.
E
The code segment will not execute because the TextBook constructor does not have a parameter for the title of the book.
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.
83
New cards
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?
A
The Drink class must have a public method named getSize that takes a String value as its parameter.
B
The Drink class must have a public method named getSize that takes no parameters.
C
The Drink class must have a public method named setSize that takes a String value as its parameter.
D
The Drink class must have a public method named setSize that takes no parameters.
E
The Drink class must have a String instance variable named size.
C
The Drink class must have a public method named setSize that takes a String value as its parameter.
84
New cards
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" ?
When someApple is an object of type Apple
When someApple is an object of type GrannySmith
When someApple is an object of type Jonagold
A
I only
B
I and II only
C
I and III only
D
II and III only
E
I, II, and III
C
I and III only
85
New cards
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?
When myPet is an object of type Pet
When myPet is an object of type Dog
When myPet is an object of type Cat
A
I only
B
I and II only
C
I and III only
D
II and III only
E
I, II, and III
E
I, II, and III
86
New cards
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
B
A Game object cannot be assigned to the BoardGame reference g2.
87
New cards
Consider the following partial class definitions.
public class Membership
{
private String id;

public Membership(String input)
{ id \= input; }

// Rest of definition not shown
}

public class FamilyMembership extends Membership
{
private int numberInFamily \= 2;

public FamilyMembership(String input)
{ super(input); }

public FamilyMembership(String input, int n)
{
super(input);
numberInFamily \= n;
}

// Rest of definition not shown
}

public class IndividualMembership extends Membership
{
public IndividualMembership(String input)
{ super(input); }

// Rest of definition not shown
}
The following code segment occurs in a class other than Membership, FamilyMembership, or IndividualMembership.
FamilyMembership m1 \= new Membership("123"); // Line 1
Membership m2 \= new IndividualMembership("456"); // Line 2
Membership m3 \= new FamilyMembership("789"); // Line 3
FamilyMembership m4 \= new FamilyMembership("987", 3); // Line 4
Membership m5 \= new Membership("374"); // Line 5
Which of the following best explains why the code segment does not compile?
A
In line 1, m1 cannot be declared as type FamilyMembership and instantiated as a Membership object.
B
In line 2, m2 cannot be declared as type Membership and instantiated as an IndividualMembership object.
C
In line 3, m3 cannot be declared as type Membership and instantiated as a FamilyMembership object.
D
In line 4, m4 cannot be declared as type FamilyMembership and instantiated as a FamilyMembership object.
E
In line 5, m5 cannot be declared as type Membership and instantiated as a Membership object.
A
In line 1, m1 cannot be declared as type FamilyMembership and instantiated as a Membership object.
88
New cards
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?
A
Line 1 will cause an error because a Road variable cannot be instantiated as an object of type Highway.
B
Line 2 will cause an error because the Road constructor is not properly called.
C
Line 3 will cause an error because a Highway variable cannot be instantiated as an object of type Road.
D
Line 4 will cause an error because the Highway constructor is not properly called.
E
The code segment compiles and runs without error.
C
Line 3 will cause an error because a Highway variable cannot be instantiated as an object of type Road.
89
New cards
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());
B
Android a \= new Android(x);
a.setServoCount(y);
System.out.println(a.getLocal());
C
Android a \= new Android(x);
a.setLocal(y);
System.out.println(a.getServoCount());
D
Android a \= new Android(y);
a.setServoCount(x);
System.out.println(a.getLocal());
E
Android a \= new Android(y);
a.setLocal(x);
System.out.println(a.getLocal());
A
Android a \= new Android(x);
a.setServoCount(y);
System.out.println(a.getServoCount());
90
New cards
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?
A
System.out.print(title + " (" + year + ") by " + artist);
B
super.printInfo(artist);
C
System.out.print(super.printInfo() + " by " + artist);
D
super();
System.out.print(" by " + artist);
E
super.printInfo();
System.out.print(" by " + artist);
E
super.printInfo();
System.out.print(" by " + artist);
91
New cards
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?
A
author \= the_author;
title \= the_title;
subject \= the_subject;
B
super(the_author, the_title);
super(the_subject);
C
subject \= the_subject;
super(the_author, the_title);
D
super(the_author, the_title);
subject \= the_subject;
E
super(the_author, the_title, the_subject);
D
super(the_author, the_title);
subject \= the_subject;
92
New cards
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?
A
b1 \== b2
B
b1.equals(b2)
C
equals(b1, b2)
D
b1.equals(b2.getLength(), b2.getWidth())
E
b1.length \== b2.length && b1.width \== b2.width
B
b1.equals(b2)
93
New cards
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?
A
(hotChocolate \= coffee)
B
(hotChocolate \== coffee)
C
hotChocolate.equals(coffee)
D
hotChocolate.equals(coffee.getTemperature())
E
hotChocolate.getTemperature().equals(coffee.getTemperature())
C
hotChocolate.equals(coffee)
94
New cards
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()
B
toString(d)
C
d.pageCount + " " + d.chapterCount
D
d.getPageCount() + " " + d.getChapterCount()
E
Document.pageCount + " " + Document.chapterCount
A
d.toString()
95
New cards
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?
A
An error occurs during compilation because a Smartphone object cannot be assigned to the Computer reference variable myPhone.
B
An error occurs during compilation because the Smartphone class has no getMemory method.
C
An error occurs during compilation because the getScreenWidth and getScreenHeight methods are not defined for the Computer object myPhone.
D
An error occurs at runtime because the Smartphone class has no getMemory method.
E
An error occurs at runtime because the getScreenWidth and getScreenHeight methods are not defined for
C
An error occurs during compilation because the getScreenWidth and getScreenHeight methods are not defined for the Computer object m
96
New cards
Consider the following class definitions.
public class C1
{
public C1()
{ /* implementation not shown */ }

public void m1()
{ System.out.print("A"); }

public void m2()
{ System.out.print("B"); }
}

public class C2 extends C1
{
public C2()
{ /* implementation not shown */ }

public void m2()
{ System.out.print("C"); }
}
The following code segment appears in a class other than C1 or C2.
C1 obj1 \= new C2();
obj1.m1();
obj1.m2();
The code segment is intended to produce the output AB. Which of the following best explains why the code segment does not produce the intended output?
A
A compile-time error occurs because obj1 is declared as type C1 but instantiated as type C2.
B
A runtime error occurs because method m1 does not appear in C2.
C
Method m1 is not executed because it does not appear in C2.
D
Method m2 is executed from the subclass instead of the superclass because obj1 is instantiated as a C2 object.
E
Method m2 is executed twice (once in the subclass and once in the superclass) because it appears in both classes.
D
Method m2 is executed from the subclass instead of the superclass because obj1 is instantiated as a C2 object.
97
New cards
Consider the following two class definitions.
public class Bike
{
private int numOfWheels \= 2;

public int getNumOfWheels()
{
return numOfWheels;
}
}

public class EBike extends Bike
{
private int numOfWatts;

public EBike(int watts)
{
numOfWatts \= watts;
}
public int getNumOfWatts()
{
return numOfWatts;
}
}
The following code segment occurs in a class other than Bike or EBike.
Bike b \= new EBike(250);
System.out.println(b.getNumOfWatts());
System.out.println(b.getNumOfWheels());
Which of the following best explains why the code segment does not compile?
A
The Bike superclass does not have a constructor.
B
There are too many arguments to the EBike constructor call in the code segment.
C
The first line of the subclass constructor is not a call to the superclass constructor.
D
The getNumOfWatts method is not found in the Bike class.
E
The getNumOfWheels method is not found in the EBike class.
D
The getNumOfWatts method is not found in the Bike class.
98
New cards
A two-dimensional array arr is to be created with the following contents.
boolean[][] arr \= {{false, true, false},
{false, false, true}};

Which of the following code segments can be used to correctly create and initialize arr ?
A
boolean arr[][] \= new boolean[2][3];
arr[0][1] \= true;
arr[1][2] \= true;
B
boolean arr[][] \= new boolean[2][3];
arr[1][2] \= true;
arr[2][3] \= true;
C
boolean arr[][] \= new boolean[3][2];
arr[0][1] \= true;
arr[1][2] \= true;
D
boolean arr[][] \= new boolean[3][2];
arr[1][0] \= true;
arr[2][1] \= true;
E
boolean arr[][] \= new boolean[3][2];
arr[2][1] \= true;
arr[3][2] \= true;
A
boolean arr[][] \= new boolean[2][3];
arr[0][1] \= true;
arr[1][2] \= true;
99
New cards
Consider the following code segment, which is intended to declare and initialize the two-dimensional (2D) String array things.
/* missing code */ \= {{"spices", "garlic", "onion", "pepper"},
{"clothing", "hat", "scarf", "gloves"},
{"plants", "tree", "bush", "flower"},
{"vehicles", "car", "boat", "airplane"}};
Which of the following could replace /* missing code */ so that things is properly declared?
A
new String[][] things
B
new(String[][]) things
C
String[] String[] things
D
String[][] things
E
\[][]String things
D
String[][] things
100
New cards
Consider the following code segment, where letters is a two-dimensional (2D) array that contains possible letters. The code segment is intended to print "DIG".
String[][] letters \= {{"A", "B", "C"},
{"D", "E", "F"},
{"G", "H", "I"}};

System.out.println( /* missing code */ );
Which of the following could replace /* missing code */ so that the code segment works as intended?
A
letters[2][1] + letters[3][3] + letters[3][1]
B
letters[2][0] + letters[2][2] + letters[1][0]
C
letters[1][2] + letters[3][3] + letters[1][3]
D
letters[1][0] + letters[2][2] + letters[2][0]
E
letters[0][1] + letters[2][2] + letters[0][2]
D
letters[1][0] + letters[2][2] + letters[2][0]