0% found this document useful (0 votes)
70 views129 pages

Csa AP Classroom Mcq

The document contains a series of multiple-choice questions (MCQs) related to programming concepts, specifically focusing on Java syntax and logic. It covers topics such as variable declarations, conditional statements, loops, and methods, providing scenarios for evaluation. Each question presents a code segment or expression and asks for the correct output or behavior based on the given code.

Uploaded by

ruotiangroup
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views129 pages

Csa AP Classroom Mcq

The document contains a series of multiple-choice questions (MCQs) related to programming concepts, specifically focusing on Java syntax and logic. It covers topics such as variable declarations, conditional statements, loops, and methods, providing scenarios for evaluation. Each question presents a code segment or expression and asks for the correct output or behavior based on the given code.

Uploaded by

ruotiangroup
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

Basic Part 1: MCQ

1.
Consider the following variable declarations and initializations.
int a = 2;
int b = 6;
int c = 3;
Which of the following expressions evaluates to false ?
(A) a < b == c < b
(B) a > b == b < c
(C) a < b != b < c
(D) a < b != c < b
(E) a > b != b > c

2.
Consider the following code segment.
boolean a = true;
boolean b = false;
System.out.print((a == !b) != false);

What is printed as a result of executing this code segment?


(A) false
(B) true
(C) 0
(D) 1
(E) Nothing is printed because the expression (a == !b) != false is an invalid
parameter to the System.out.print method.

3.
Consider the following expression.

(3 + 4 == 5) != (3 + 4 >= 5)

What value, if any, does the expression evaluate to?


(A) true
(B) false
(C) 5
(D) 7
(E) No value; relational operators cannot be used on arithmetic expressions.
4.
Consider the following code segment.

int quant = 20;


int unitPrice = 4;
int ship = 8;
int total;
if (quant > 10)
{
unitPrice = 3;

if (quant > 20)


{
ship = 0;
}

total = quant * unitPrice + ship;

What is the value of total after this code segment has been executed?
A. 20
B. 60
C. 68
D. 80
E. 88

5.
Consider the following code segment.

int a = 1;
int b = 0;
int c = -1;

if ((b + 1) == a)
{
b++;
c += b;
}

if (c == a)
{
a--;
b = 4;
}

What are the values of a, b, and c after this code segment has been executed?
A. a = 0, b = 4, and c = 0
B. a = 0, b = 4, and c = 1
C. a = 1, b = 0, and c = -1
D. a = 1, b = 1, and c = 0
E. a = 1, b = 1, and c = 1
6.
Consider the following code segment.
int m = 8;
int n = 3;

if (m + n > 10)
{
System.out.print(m + n);

if (m - n > 0)
{
System.out.print(m - n);
}

What, if anything, is printed as a result of executing the code segment?


A. Nothing is printed.
B. 5
C. 11
D. 115
E. 511
7.
In the code segment below, the int variable temp represents a temperature in degrees Fahrenheit. The code segment is
intended to print a string based on the value of temp. The following table shows the string that should be printed for
different temperature ranges.
Temperature Range String to Print
31 and below "cold"
32–50 "cool"
51–70 "moderate"
71 and above "warm"

String weather;
if (temp <= 31)
{
weather = "cold";
} else
{
weather = "cool";
}
if (temp >= 51)
{
weather = "moderate";
} else
{
weather = "warm";
}
System.out.print(weather);

Which of the following test cases can be used to show that the code does NOT work as intended?

I. temp = 30
II. temp = 51
III. temp = 60
A. I only
B. II only
C. I and II only
D. II and III only
E. I, II, and III
8.
Consider the following code segment, which is intended to set the Boolean variable inRange to true if the integer value
num is greater than min value and less than max value. Otherwise inRange is set to false. Assume that inRange, num,
min, and max have been properly declared and initialized.

boolean isBigger;
boolean isSmaller;
boolean inRange;

if (num < max)


{
isSmaller = true;
}
else
{
isSmaller = false;
}

if (num > min)


{
isBigger = true;
}
else
{
isBigger = false;
}

if (isBigger == isSmaller)
{
inRange = true;
}
else
{
inRange = false;
}

Which of the following values of num, min, and max can be used to show that the code does NOT work as intended?
A. num = 20, min = 30, max = 50
B. num = 30, min = 20, max = 40
C. num = 40, min = 10, max = 40
D. num = 50, min = 50, max = 50
E. num = 60, min = 40, max = 50
9.
Assume that the int variables a, b, c, and low have been properly declared and initialized. The code segment below is
intended to print the sum of the greatest two of the three values but does not work in some cases.

if (a > b && b > c)


{
low = c;
}

if (a > b && c > b)


{
low = b;
}
else
{
low = a;
}

System.out.println(a + b + c - low);

For which of the following values of a, b, and c does the code segment NOT print the correct value?
A. a = 1, b = 1, c = 2
B. a = 1, b = 2, c = 1
C. a = 1, b = 2, c = 3
D. a = 2, b = 2, c = 2
E. a = 3, b = 2, c = 1

10

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?

A. x < 100
B. x <= 100
C. x > 10
D. x >= 10
E. x != 10
11

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?

A. while (num > 0)


B. while (num >= 0)
C. while (num > 1)
D. while (num > 2)
E. while (num > sum)

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


A. 21
B. 161116
C. 161161
D. 16111621
E. Nothing is printing because of an infinite loop.
13
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?
A. 6
B. 5
C. 4
D. 1
E. 0

14
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?
A. for (int k = 0; k < 100; k += 2)
{
total += k + 1;
}

B. for (int k = 1; k < 101; k += 2)


{
total += k - 1;
}

C. for (int k = 0; k <= 101; k += 2)


{
total += k + 1;
}

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

E.
for (int k = 1; k <= 101; k += 2)
{
total += k - 1;
}
15
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?

A. The output of the code segments is the same because the loops in each code segment terminate when i is
10.
B. The output of the code segments is the same because the loops in both code segments iterate 10 times.
C. The output of the code segments is different because code segment I iterates from i = 0 to i = 9 and code
segment II iterates from i = 1 to i = 10.
D. The output of the code segments is different because code segment I iterates from i = 0 to i = 10 and code
segment II iterates from i = 1 to i = 11.
E. Neither code segment produces output because both loop conditions are initially false.

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

A. An additional value will be printed because the for loop will iterate one additional time.
B. One fewer value will be printed because the for loop will iterate one fewer time.
C. There will be no change to the program output because the loop will iterate the same number of times.
D. An infinite loop will occur because the loop condition will never be false.
E. The body of the loop will not execute at all because the loop condition will initially be false.
17
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?

A. c <= 2
B. c < 3
C. c <= 3
D. c > 2
E. c >= 3

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

A. The output of the code segment will be unchanged.


B. The string "hello" will be printed three fewer times because the inner loop will iterate one fewer time for
each iteration of the outer loop.
C. The string "hello" will be printed four fewer times because the inner loop will iterate one fewer time for
each iteration of the outer loop.
D. The string "hello" will be printed three additional times because the inner loop will iterate one additional
time for each iteration of the outer loop.
E. 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.
19
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?

A. The numbers will be printed in the reverse order as they were in the original code segment because the
outer loop will occur in reverse order.
B. Five additional values will be printed because the outer for loop will iterate one additional time.
C. An infinite loop will occur because the termination condition of the loop will never be reached.
D. There will be no change to the program output.
E. Nothing will be printed because the body of the outer for loop will not execute at all.

20
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?
A. 0
B. 5
C. 6
D. 7
E. 50
21
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?

A. 1
B. 7
C. 8
D. 35
E. More than 35 times, because the code segment will cause an infinite loop.

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


A. 15
B. 16
C. 20
D. 24
E. 25
Basic Part 2: MCQ
1
Consider the method digitSum below, which takes a positive integer parameter as input.
public int digitSum(int num)
{
int total = 0;
while (num > 0)
{
total += num % 10;
num /= 10;
}
return total;
}
Which of the following code segments could replace the while loop in the method digitSum without
changing the value returned by the method?
I.
for (int h = 0; h < num; h++)
{
total += num % 10;
num /= 10;
}

II.
for (int j = num; j > 0; j--)
{
total += j % 10;
}

III.
for (int k = num; k > 0; k /= 10)
{
total += k % 10;
}
A. I only
B. II only
C. III only
D. I and II
E. II and III
2
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

Which of the following can be used to replace /* missing loop header */ so that the code segment will work as
intended?

A. for (int h = 0; h < k; h++)


B. for (int h = 1; h < k + 1; h++)
C. for (int h = 0; h < 3; h++)
D. for (int h = k; h >= 0; h--)
E. for (int h = k; h <= 0; h--)
3

The method addItUp(m, n) is intended to print the sum of the integers greater than or equal to m and less than
or equal to n. For example, addItUp(2, 5) should return the value of 2 + 3 + 4 + 5.

/* missing precondition */

public static int addItUp(int m, int n)


{
int sum = 0;
for (int j = m; j <= n; j++)
{
sum += j;
}
return sum;
}

Which of the following is the most appropriate precondition for the method?
A. /* Precondition: m <= n */
B. /* Precondition: n <= m */
C. /* Precondition: m >= 0 and n >= 0 */
D. /* Precondition: m <= 0 and n <= 0 */
E. /* Precondition: m <= 0 and n >= 0 */
One-D Array : MCQ
1
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} ?

A.arr[0] = 10;
arr[1] = 10;
B. arr[1] = 10;
arr[2] = 10;
C. arr[0, 1] = 10;
D.arr[1, 2] = 10;
E. arr = 10, 10, 3, 4, 5;

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

I int[] arr = {0, 0, 0, 0};


II int[] arr = new int[0];
III int[] arr = new int[4];

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

I checkString(new String[]);
II checkString(new String[0]);
III String[] str = {"cat", "dog"}; checkString(str);

A. II only
B. III only
C. I and III only
D. II and III only
E. I, II, and III

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

A. {10, 20, 30, 70, 120}


B. {10, 20, 50, 90, 50}
C. {10, 20, 50, 90, 140}
D. {10, 30, 60, 100, 50}
E. {10, 30, 60, 100, 150}
5
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?

A. 2
B. 1
C. 0
D. -4
E. Nothing is printed because the code segment causes a runtime error.

6
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]);

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

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


B. In the for loop header, the initial value of j should be 2.
C. The for loop condition should be j < fibs.length - 1.
D. The for loop condition should be j < fibs.length + 1.
E. The for loop should increment j by 2 instead of by 1.

8
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?
A. for (int x : numbers)
{
System.out.println(numbers[x]);
}

B for (int x : numbers)


{
System.out.println(numbers);
}

C for (int x : numbers)


{
System.out.println(x);
}

D for (numbers : int x)


{
System.out.println(numbers[x]);
}

E for (numbers : int x)


{
System.out.println(x);
}
9
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 ?

A. Both code segment I and code segment II will print 45.


B. Both code segment I and code segment II will print 45678.
C. Code segment I will cause an ArrayIndexOutOfBoundsException and code segment II will print 45.
D. Code segment I will cause an ArrayIndexOutOfBoundsException and code segment II will print 45678.
E. Both code segment I and code segment II will cause an ArrayIndexOutOfBoundsException.

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

A. for (int y = 0; y <= arr.length; y++)


B. for (int y = 0; y < arr.length; y++)
C. for (int y = x; y < arr.length; y++)
D. for (int y = x + 1; y < arr.length; y++)
E. for (int y = x + 1; y <= arr.length; y++)
11
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?

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


B. for (int k = 0; k < numArr.length; k++)
C. for (int k = 0; k < numArr.length / 2; k--)
D. for (int k = numArr.length - 1; k >= 0; k--)
E. for (int k = numArr.length - 1; k >= 0; k++)

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

A. The array values must contain at least one negative integer.


B. The array values must contain at least one nonnegative integer.
C. The array values must contain at least one positive integer.
D. No precondition is needed. The method will never work as intended.
E. No precondition is needed. The method will always work as intended.
Two-D Array: MCQ
1

A two-dimensional array myArray is to be created with the following contents.

{{0, 0, 3},
{0, 0, 0},
{7, 0, 0}}

Which of the following code segments can be used to correctly create and initialize myArray ?
I
int myArray[][] = new int[3][3];
myArray[0][2] = 3;
myArray[2][0] = 7;

II
int myArray[][] = new int[3][3];
myArray[0][2] = 7;
myArray[2][0] = 3;

III
int myArray[][] = {{0, 0, 3}, {0, 0, 0}, {7, 0, 0}};

A. I only
B. II only
C. III only
D. I and III
E. II and III

Consider the following code segment, which is intended to create and initialize the two-dimensional (2D)
integer array num so that columns with an even index will contain only even integers and columns with an
odd index will contain only odd integers.

int[][] num = /* missing code */;

Which of the following initializer lists could replace /* missing code */ so that the code segment will work
as intended?

A. {{0, 1, 2}, {4, 5, 6}, {8, 3, 6}}


B. {{1, 2, 3}, {3, 4, 5}, {5, 6, 7}}
C. {{1, 3, 5}, {2, 4, 6}, {3, 5, 7}}
D. {{2, 1, 4}, {5, 2, 3}, {2, 7, 6}}
E. {{2, 4, 6}, {1, 3, 5}, {6, 4, 2}}
3

Consider the following code segment, which is intended to display "cat".

String[][] keyboard = {{"q", "w", "e", "r", "t"},

{"a", "s", "d", "f", "g"},

{"z", "x", "c", "v", "b"}};

System.out.println(/* missing expression */);

Which of the following can replace /* missing expression */ so that the code segment works as intended?

A. keyboard[12] + keyboard[5] + keyboard[4]


B. keyboard[13] + keyboard[6] + keyboard[5]
C. keyboard[2][2] + keyboard[1][0] + keyboard[0][4]
D. keyboard[2][2] + keyboard[0][1] + keyboard[4][0]
E. keyboard[3][3] + keyboard[2][1] + keyboard[1][5]

Consider the following code segment, where twoD is a two-dimensional (2D) String array. The code
segment is intended to display "JAVA".
System.out.print(twoD[2][1]);
System.out.print(twoD[3][2]);
System.out.print(twoD[1][1]);
Which of the following code segments properly declares and initializes twoD so that the code segment
works as intended?
A.
String[][] twoD = {{"V", "AV", "J"},
{"JA", "VA", "A"},
{"JA", "J", "JAV"},
{"AV", "V", "A"}};
B.
String[][] twoD = {{"VA", "J", "A", "V"},
{"J", "A", "V", "A"},
{"AV", "A", "JA", "V"}};
C.
String[][] twoD = {{"VA", "J", "V", "JA"},
{"J", "JA", "A", "VA"},
{"J", "VA", "A", "V"}};
D.
String[][] twoD = {{"A", "VA", "J", "V"},
{"VA", "A", "JA", "V"},
{"VA", "J", "A", "V"}};

E.
String[][] twoD = {{"A", "V"},
{"VA", "J"},
{"J", "A"},
{"A", "AV"}};
5
Consider the following code segment.
int[][] multi = new int[4][4];
for (int rows = 0; rows < 4; rows++)
{
for (int cols = 0; cols < 4; cols++)
{
if (cols == 0)
{
multi[rows][cols] = 0;
}
else if (cols == 1)
{
multi[rows][cols] = 1;
}
else if (cols == 2)
{
multi[rows][cols] = 2;
}
if ((rows % 2 == 0) && (cols % 2 == 0))
{
if ((rows >= 2) && (cols <= 2))
{
multi[rows][cols] = 9;
}
}
}
}
As a result of executing the code segment, how many elements in the two-dimensional (2D) array multi will
store the value 9 ?
A. 0
B. 1
C. 2
D. 4
E. 6
6
Consider the following code segment.
int[][] mat = {{10, 15, 20, 25},
{30, 35, 40, 45},
{50, 55, 60, 65}};
for (int[] row : mat)
{
for (int j = 0; j < row.length; j += 2)
{
System.out.print(row[j] + " ");
}
System.out.println();
}
What, if anything, is printed as a result of executing the code segment?

A. 10 15 20 25
B.
10 20
30 40
50 60
C.
10 15 20 35
30 35 40 45
50 55 60 65
D.
Nothing is printed, because an ArrayIndexOutOfBoundsException is thrown.
E. Nothing is printed, because it is not possible to use an enhanced for loop on a two-dimensional array.
7
Consider the following code segment.
int[][] arr = {{3, 2, 1}, {4, 3, 5}};
for (int row = 0; row < arr.length; row++)
{
for (int col = 0; col < arr[row].length; col++)
{
if (col > 0)
{
if (arr[row][col] >= arr[row][col - 1])
{
System.out.println("Condition one");
}
}
if (arr[row][col] % 2 == 0)
{
System.out.println("Condition two");
}
}
}
As a result of executing the code segment, how many times are "Condition one" and "Condition
two" printed?
A. "Condition one" is printed twice, and "Condition two" is printed twice.
B. "Condition one" is printed twice, and "Condition two" is printed once.
C. "Condition one" is printed once, and "Condition two" is printed twice.
D. "Condition one" is printed once, and "Condition two" is printed once.
E. "Condition one" is never printed, and "Condition two" is printed once.

8
Consider the following code segment.
int[][] arr = {{1, 3, 4},
{4, 5, 3}};
int max = arr[0][0];
for (int row = 0; row < arr.length; row++)
{
for (int col = 0; col < arr[row].length; col++)
{
int temp = arr[row][col];
if (temp % 2 == 0)
{
arr[row][col] = temp + 1; // line 11
}
if (temp > max)
{
max = temp;
}
}
}
System.out.println(max);
How many times will the statement in line 11 be executed as a result of executing the code segment?
A. 2
B. 3
C. 4
D. 5
E. 6
9
Consider the following method, sumRows, which is intended to traverse all the rows in the two-
dimensional (2D) integer array num and print the sum of all the elements in each row.

public static void sumRows(int[][] num)


{
for (int[] r : num)
{
int sum = 0;
for (int j = 0; j < num.length; j++)
{
sum += r[j];
}
System.out.print(sum + " ");
}
}
For example, if num contains {{3, 5}, {6, 8}}, then sumRows(num) should print "8 14 ".
The method does not always work as intended. For which of the following two-dimensional array input
values does sumRows NOT work as intended?
A. {{0, 1}, {2, 3}}
B. {{10, -18},{48, 17}}
C. {{-5, 2, 0}, {4, 11, 0}}
D. {{4, 1, 7}, {-10, -11, -12}}
E. {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

10
Consider the following code segment, where num is a properly declared and initialized integer variable. The
following code segment is intended to set foundRow and foundCol to the row and column indexes of an
array element containing num. The code segment does not work as intended.
int[][] arr = {{10, 11, 12, 13},
{22, 24, 26, 28},
{15, 16, 17, 18},
{40, 41, 42, 43}};
int foundRow = -1;
int foundCol = -1;
for (int j = 0; j < arr.length; j++)
{
for (int k = 1; k < arr[0].length; k++)
{
if (arr[j][k] == num)
{
foundRow = j;
foundCol = k;
}
}
}
Which of the following values for num can be used as a test case to show that the code segment does not
work as intended?
A. 12
B. 15
C. 24
D. 41
E. 43
String: MCQ
1
Consider the following method.

public static int mystery(String string1, String string2)


{
String temp = string1;
int position = 0;
int result = 0;
while(temp.indexOf(string2) >= 0)
{
position = temp.indexOf(string2);
result++;
temp = temp.substring(position + 1);
}
return result;
}

The following code segment appears in another method in the same class.

System.out.println(mystery("Mississippi", "si"));

What, if anything, is printed as a result of executing the code segment?


A. 0
B. 1
C. 2
D. 3
E. Nothing is printed.
2

Consider the following method.

public String mystery(String word, int num)


{
String result = "";
for (int k = num; k >= 0; k--)
{
result += word.substring(0, k);
}
return result;
}

What is returned as a result of the call mystery("computer", 3) ?


A. ccocom
B. comcoc
C. ccocomcomp
D. compcomcoc
E. comcomcomcom

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


A. 0
B. 5
C. 0 5
D. 0 6
E. 1 6
4

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?
A. 0 <= index < phrase.length()
B. 0 <= index < key.length()
C. 0 <= index < phrase.length() + key.length()
D. 0 <= index <= phrase.length() - key.length()
E. 0 <= index < phrase.length() – index

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?

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


B. /* Precondition: 0 < j and 0 < k */
C. /* Precondition: 0 <= j and 0 <= k */
D. /* Precondition: j <= k */
E. /* Precondition: 0 <= j <= k <= oldString.length() */
6
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?

A. 0
B. values[0]
C. values[1]
D. Integer.MIN_VALUE
E. Integer.MAX_VALUE
Class : MCQ
1
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?
A private int numerator;
private int denominator;

private double fractionToDecimal()


{
return (double) numerator / denominator;
}

B private int numerator;


private int denominator;

public double fractionToDecimal()


{
return (double) numerator / denominator;
}

C public int numerator;


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

D public double fractionToDecimal()


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

E public double fractionToDecimal()


{
public int numerator;
public int denominator;
return (double) numerator / denominator;
}
2
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?
A private String str;
private Thing(String s)
{ /* implementation not shown */ }

private void helper()


{ /* implementation not shown */ }

B private String str;


public Thing(String s)
{ /* implementation not shown */ }

private void helper()


{ /* implementation not shown */ }

C private String str;


public Thing(String s)
{ /* implementation not shown */ }
public void helper()
{ /* implementation not shown */ }

D public String str;


private Thing(String s)
{ /* implementation not shown */ }

public void helper()


{ /* implementation not shown */ }

E public String str;

public Thing(String s)
{ /* implementation not shown */ }

public void helper()


{ /* implementation not shown */ }
3
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?


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

B public class Employee


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

C public class Employee


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

D private class Employee


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

E private class Employee


{
private String name;
private double salary;
// constructor and methods not shown

}
4

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?


A. Student max = new Student ("Max", 10, 3.75);
B. Student max = new Student (3.75, "Max", 10);
C. Student max = new Student (3.75, 10, "Max");
D. Student max = new Student (10, "Max", 3.75);
E. Student max = new Student (10, 3.75, "Max");
5

Consider the following class definition. Each object of the class Employee will store the employee’s name as
name, the number of weekly hours worked as wk_hours, and hourly rate of pay as pay_rate.
public class Employee
{
private String name;
private int wk_hours;
private double pay_rate;

public Employee(String nm, int hrs, double rt)


{
name = nm;
wk_hours = hrs;
pay_rate = rt;
}
public Employee(String nm, double rt)
{
name = nm;
wk_hours = 20;
pay_rate = rt;
}
}

Which of the following code segments, found in a class other than Employee, could be used to correctly create an
Employee object representing an employee who worked for 20 hours at a rate of $18.50 per hour?
I. Employee e1 = new Employee("Lili", 20, 18.5);
II. Employee e2 = new Employee("Steve", 18.5);
III. Employee e3 = new Employee("Carol", 20);
A. I only
B. III only
C. I and II only
D. I and III only
E. I, II, and III
6

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?
A private Person()
{
name = n;
}

B private Person(String n)
{
name = n;
}

C public Person()
{
name = n;
}

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

E public Person(String name)


{
String n = name;
}
7

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?

A. The return type for the isOlderThan5 method should be void.


B. The return type for the isOlderThan5 method should be String.
C. The return type for the isOlderThan5 method should be int.
D. The isOlderThan5 method is missing a return statement for the case when age is less than or equal to 5.
E. The isOlderThan5 method should receive the variable age as a parameter.
8

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?

A. The class is missing a mutator method.


B. The class is missing an accessor method.
C. The accessor method is missing a return type.
D. The accessor method returns a variable other than an instance variable.
E. The instance variables should be designated public instead of private.
9

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?

A. The getH method should have a double parameter.


B. The getH method should have an int parameter.
C. The getH method should return newH instead of h.
D. The getH method should have a return type of int.
E. The getH method should have a return type of void.
10

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?
A. In line 10, the appendIt method should be declared as return type String.
B. Line 12 should be changed to str = s + str;
C. Line 12 should be changed to str = str + s;
D. Line 12 should be changed to return s + str;
E. Line 12 should be changed to return str + s;.
11

Consider the class definition below. The method levelUp is intended to increase a Superhero object’s strength
attribute by the parameter amount. The method does not work as intended.

public class Superhero


{
private String name;
private String secretIdentity;
private int strength;
public Superhero(String realName, String codeName)
{
name = realName;
secretIdentity = codeName;
strength = 5;
}

public int levelUp(int amount) // line 14


{
strength += amount; // line 16
}

Which of the following changes should be made so that the levelUp method works as intended?

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


B. In line 14, amount should be declared as type void.
C. Line 16 should be changed to strength + amount;
D. Line 16 should be changed to return strength + amount;
E. Line 16 should be changed to return amount;.
12
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?

A. In lines 14 and 18, change < to >.


B. In lines 14 and 18, change < to <=.
C. In line 16, change score1 to num1 and in line 18, change score2 to num2.
D. In line 18, change else if to if.
E. In line 18, change else if to else.
13

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?

A. if (years >= 10)


{
bonus *= 2;
}
return salary + bonus;

B. if (yearsOfService >= 10)


{
bonus *= 2;
}
return salary + bonus;

C. return salary + bonus;

D. if (years >= 10)


{
bonus *= 2;
}
return sal + bonus;

E. if (yearsOfService >= 10)


{
bonus *= 2;
}
return sal + bonus;
14

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?
A. String prev = w;
return weather;
B. String prev = weather;
return w;
C. String prev = w;
return prev;
D. weather = w;
String prev = weather;
return prev;
E. String prev = weather;
weather = w;
return prev;
15

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 */.
I. return one > other.one;
II. return one > other.getOne();
III. return getOne() > other.one;
Which of the following replacements for /* missing code */ can be used so that isGreater will work as
intended?
A. I only
B. II only
C. III only
D. I and II only
E. I, II and III
16

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?

A. The code segment does not compile because the setStatus method should be called on an object of the
class Gadget, not on the class itself.
B. The code segment does not compile because the static variable status is not properly initialized.
C. 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.
D. The code segment creates two Gadget objects a and b. After executing the code segment, the object a has
a status value of 3 and the object b has a status value of 3.
E. The code segment creates two Gadget objects a and b. After executing the code segment, the object a has
a status value of 3 and the object b has a status value of 10.
17

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?

A. Both numOunces and numSold can be accessed and updated.


B. Both numOunces and numSold can be accessed, but only numOunces can be updated.
C. Both numOunces and numSold can be accessed, but only numSold can be updated.
D. numSold can be accessed but not updated; numOunces cannot be accessed or updated.
E. numSold can be accessed and updated; numOunces cannot be accessed or updated.
18
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);

Which of the following best describes the behavior of the code segment?

A. The code segment does not compile, because it is not possible to create the object large from outside the
UnitsHandler class.
B. The code segment does not compile, because it attempts to change the values of private variables from
outside the UnitsHandler class.
C. The code segment does not compile, because the update method should be called on the object large
instead of on the UnitsHandler class.
D. The code segment creates a UnitsHandler object called large and sets the static variable unitsPerContainer
to 100. The static variables containers and totalUnits each retain the default value 0.
E. The code segment creates a UnitsHandler object called large and sets the static variables unitsPerContainer,
containers, and totalUnits to 100, 8, and 800, respectively.
19

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?
A. The deposit method must have a return statement.
B. In the deposit method, the variable balance should be replaced by the variable initialBalance.
C. In the deposit method, the variable balance is declared as a local variable and is different from the
instance variable balance.
D. The method header for the deposit method should be public void deposit(amount).
E. The variable balance must be passed to the deposit method.
20

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?
A. The code segment will not compile because an object cannot be passed as a parameter in a call to println.
B. The code segment will not compile because firstName, lastName, and age are names of instance variables
and cannot be used as parameter names in the constructor.
C. The code segment will not compile because the constructor needs to ensure that age is not negative.
D. 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 instance variables inside the constructor.
E. 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.
21
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?

A. The constructor should have a return type of String.


B. The constructor should have a return type of void.
C. The instance variable str should be designated public.
D. The variable str should be designated public in the constructor.
E. The variable str should not be declared as a String in the constructor.
22

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?
A. Andrew
B. Benjamin
C. Same
D. Nothing is printed because the method heightInInches cannot be called on this.
E. Nothing is printed because the compareHeights method in the Person class cannot take a Person object as
a parameter.
23
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());
}

A. I only
B. II only
C. III only
D. I and II
E. II and III
24
Consider the following methods, which appear in the same class.
public void slope(int x1, int y1, int x2, int y2)
{
int xChange = x2 - x1;
int yChange = y2 - y1;
printFraction(yChange, xChange);
}
public void printFraction(int numerator, int denominator)
{
System.out.print(numerator + "/" + denominator);
}
Assume that the method call slope(1, 2, 5, 10) appears in a method in the same class. What is printed as a result of the
method call?
(A) 8/4
(B) 5/1
(C) 4/8
(D) 2/1
(E) 1/5

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

27
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);
28
Consider the following method.
public void doSomething()
{
System.out.println("Something has been done");
}
Each of the following statements appears in a method in the same class as doSomething. Which of the
following statements are valid uses of the method doSomething ?
I. doSomething();
II. String output = doSomething();
III.System.out.println(doSomething());
(A) I only
(B) II only
(C) I and II only
(D) I and III only
(E) I, II, and III

29
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
30
Consider the following class declaration.
public class GameClass
{
private int numPlayers;
private boolean gameOver;
public Game()
{
numPlayers = 1;
gameOver = false;
}
public void addPlayer()
{
numPlayers++;
}
public void endGame()
{
gameOver = true;
}
}
Assume that the GameClass object game has been properly declared and initialized in a method in a class
other than GameClass. Which of the following statements are valid?
I. game.numPlayers++;
II. game.addPlayer();
III. game.gameOver();
IV. game.endGame();
(A) IV only
(B) I and III only
(C) I and IV only
(D) II and IV only
(E) II, III, and IV only

31
Consider the following class definition.
public class Element{
public static int max_value = 0;
private int value;
public Element (int v) (
value = v;
if (value > max_value) {
max_value = value;
}
}
}
The following code segment appears in a class other than Element.
for (int i = 0; i < 5; i++) {
int k = (int) (Math.random() * 10 + 1);
if (k >= Element.max_value) {
Element e = new Element(k);
}
}
Which of the following best describes the behavior of the code segment?
(A) Exactly 5 Element objects are created.
(B) Exactly 10 Element objects are created.
(C) Between 0 and 5 Element objects are created, and Element .max_value is increased only for the first object created.
(D) Between 1 and 5 Element objects are created, and Element .max_value is increased for every object created.
(E) Between 1 and 5 Element objects are created, and Element .max_value is increased for at least one object created.
ArrayList: MCQ
1
Consider the following statement, which is intended to create an ArrayList named a to store only elements of type Thing.
Assume that the Thing class has been properly defined and includes a no-parameter constructor.

ArrayList<Thing> a = /* missing code */;

Which of the following can be used to replace /* missing code */ so that the statement works as intended?

A. new Thing()
B. new ArrayList<Thing>()
C. new ArrayList(Thing)
D. new ArrayList(<Thing>)
E. new ArrayList<>(Thing)

2
Consider the following statement, which is intended to create an ArrayList named numbers that can be used to store
Integer values.

ArrayList<Integer> numbers = /* missing code */;

Which of the following can be used to replace /* missing code */ so that the statement works as intended?

I new ArrayList()
II new ArrayList<Integer>
III new ArrayList<Integer>()

A. III only
B. I and II only
C. I and III only
D. II and III only
E. I, II, and III

3
Consider the following statement, which is intended to create an ArrayList named arrList to store elements only of type
String.

/* missing code */ = new ArrayList<String>();

Which of the following can be used to replace /* missing code */ so that the statement works as intended?

A. ArrayList arrList()
B. ArrayList arrList
C. ArrayList<> arrList
D. ArrayList arrList<String>
E. ArrayList<String> arrList
4
Consider the following code segment.

ArrayList<Integer> nums = new ArrayList<>();


nums.add(3);
nums.add(2);
nums.add(1);
nums.add(0);
nums.add(0, 4);
nums.set(3, 2);
nums.remove(3);
nums.add(2, 0);

Which of the following represents the contents of nums after the code segment has been executed?

A. [2, 4, 3, 2, 0]
B. [3, 2, 0, 1, 0]
C. [4, 2, 0, 2, 0]
D. [4, 3, 0, 2, 0]
E. [4, 3, 0, 3, 0]

5
Consider the following code segment.

ArrayList<String> syllables = new ArrayList<String>();


syllables.add("LA");
syllables.add(0, "DI");
syllables.set(1, "TU");
syllables.add("DA");
syllables.add(2, syllables.get(0));
syllables.remove(1);
System.out.println(syllables.toString());

What is printed as a result of executing the code segment?

A. [DI, DA, DI]


B. [DI, DI, DA]
C. [LA, LA, DA]
D. [TU, DI, DA]
E. [TU, TU, DA]
6
Consider the following code segment.

ArrayList<Integer> vals = new ArrayList<Integer>();


vals.add(vals.size(), vals.size());
vals.add(vals.size() - 1, vals.size() + 1);
vals.add(vals.size() - 2, vals.size() + 2);
System.out.println(vals.toString());

What is printed as a result of executing the code segment?

A. [0, 1, 2]
B. [0, 2, 4]
C. [1, 2, 3]
D. [2, 1, 0]
E. [4, 2, 0]

7
Consider the following code segment.

ArrayList<Integer> myList = new ArrayList();


for (int i = 0; i < 4; i++)
{
myList.add(i + 1);
}

for (int i = 0; i < 4; i++)


{
if (i % 2 == 0)
{
System.out.print(myList.get(i) + " ");
}
}

What output is produced as a result of executing the code segment?

A. 0123
B. 1234
C. 02
D. 13
E. 24
8
Consider the following code segment.

ArrayList<String> words = new ArrayList<String>();


words.add("mat");
words.add("new");
words.add("open");
words.add("pet");
int i = 0;
while (i < words.size())
{
words.remove(i);
i++;
}
System.out.println(words.toString());

What is printed when the code segment is executed?

A. []
B. [new, pet]
C. [open, pet]
D. [new, open, pet]
E. [mat, new, open, pet]

9
Consider the following code segment.

ArrayList<String> arrList = new ArrayList<String>();


arrList.add("A");
arrList.add("B");
arrList.add("C");
arrList.add("D");

for (int i = 0; i < arrList.size(); i++)


{
System.out.print(arrList.remove(i));
}

What, if anything, is printed as a result of executing the code segment?

A. AC
B. BD
C. ABC
D. ABCD
E. Nothing is printed.
10
Consider the following method definition. The method isReversed is intended to return true if firstList and
secondList contain the same elements but in reverse order, and to return false otherwise.

/** Precondition: firstList.size() == secondList.size() */

public static boolean isReversed(ArrayList<Integer> firstList, ArrayList<Integer>


secondList)
{
for (int j = 0; j < firstList.size() / 2; j++)
{
if(firstList.get(j)
!=secondList.get(secondList.size() - 1 - j))
{
return false;
}
}
return true;
}

The method does not always work as intended. For which of the following inputs does the method NOT return the correct
value?

A. When firstList is {1, 3, 3, 1} and secondList is {1, 3, 3, 1}


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

11
In the code segment below, myList is an ArrayList of integers. The code segment is intended to remove all elements
with the value 0 from myList.

int j = 0;
while (j < myList.size())
{
if (myList.get(j) == 0)
{
myList.remove(j);
}
j++;
}

The code segment does not always work as intended. For which of the following lists does the code segment NOT
produce the correct result?

A. {0, 1, 2, 3}
B. {0, 1, 0, 2}
C. {1, 0, 0, 2}
D. {1, 2, 3, 0}
E. {1, 2, 3, 4}
12
In the code segment below, numList is an ArrayList of integers that is sorted in descending order. The code
segment is intended to insert the integer value val into numList so that numList is still sorted in descending
order.

int j = 0;
while (val != numList.get(j))
{
j++;
}
numList.add(j, val);

The code segment does not always work as intended. Assuming that numList has been initialized to {3, 2, 1,
0}, for which value of val does the code segment NOT produce the expected result?

A. 4
B. 3
C. 2
D. 1
E. 0

13
Consider the method sequentialSearch, which takes an ArrayList of Integer elements and an int value as
parameters and returns the index of the first appearance of the target value in the list or -1 if the target value does not
appear in the list.

public static int sequentialSearch(ArrayList<Integer>


elements, int target)
{
for (int j = 0; j < elements.size(); j++) // Line 3
{
if (elements.get(j) == target)
{
return j;
}
}
return -1;
}

Which of the following explains how replacing Line 3 with for (int j = (elements.size() - 1); j >= 0; j--) will affect the
behavior of sequentialSearch?

A. The modification has no effect: the modified method will continue to return the index of the first appearance of the
target value in the list, or -1 if the target value does not appear in the list.
B. The modified method will return the index of the last appearance of the target value in the list, or -1 if the target value
does not appear in the list.
C. The modified method will throw an ArrayIndexOutOfBoundsException.
D. The modified method will return -1 regardless of the inputs.
E. The modified method will not compile.
14
Consider the following search method.

public static int search(int[] arr, int target)


{
int result = -1;
for (int j = 0; j < arr.length; j++)
{
if (arr[j] == target)
{
result = j; // Line 8
}
}
return result;
}

Which of the following describes the effect of replacing the statement in line 8 of the method with result =
arr[j]; ?

A. The modified method will return the index of the first occurrence of target in arr.
B. The modified method will return the index of the last occurrence of target in arr.
C. The modified method will return target if target appears in arr and will return -1 otherwise.
D. The modified method will return -1 if target appears in arr and will return target otherwise.
E. The modified method will return -1 for all possible inputs.
15
Consider the method seqSearch, which implements a sequential search algorithm.

public int seqSearch(int[] arr, int target)


{
for (int j = 0; j < arr.length; j++)
{
if (arr[j] == target)
{
return j;
}
}
return -1;
}
Consider another method, seqSearch2, which modifies seqSearch to use an enhanced for loop.

public int seqSearch2(int[] arr, int target)


{
for (int j : arr)
{
if (j == target)
{
return j;
}
}
return -1;
}

Which of the following best describes the difference in the behavior of seqSearch2 relative to seqSearch as a result of the
modification?

A. The modification in seqSearch2 has no effect: seqSearch2 will always behave exactly as seqSearch does.
B. The modification in seqSearch2 will cause a compilation error.
C. The modification in seqSearch2 will cause an ArrayIndexOutOfBoundsException to be thrown for some inputs.
D. The modification in seqSearch2 will cause -1 to be returned for all inputs.
E. The modification in seqSearch2 will cause the value of target to be returned instead of the index of target in cases
where target appears in arr.
16
Consider the following method countNegatives, which searches an ArrayList of integer objects and returns the number of
elements in the list that are less than 0.
public static int countNegatives(ArrayList<Integer> arr)
{
int count = 0;
for (int j = 0; j < arr.size(); j++) // Line 4
{
if (arr.get(j) < 0)
{
count++;
}
}
return count;
}
Which of the following best explains the impact to the countNegatives method when, in line 4, j < arr. size ()
is replaced with j <= arr.size() – 1?

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


(B) It causes the method to ignore the last element in arr.
(C) It causes the method to throw an indexOutOf Bounds exception.
(D) It reduces the size of arr by 1 and the last element will be removed.
(E) It changes the number of times the loop executes, but all indexes in arr will still be accessed.

17
Consider the following method findvalue; which takes an ArrayList of string elements and a string value as
parameters and returns true if the string value is found in the list and false otherwise.
public static boolean findValue(ArrayList<String> arrz String key)
{
for (int j = 0; j < arr.size(); j++) // Line 3
{
if (arr.get(j).equals(key))
{
return true;
}
}
return false;
}
Which of the following best explains the impact to the findvalue method when, in line 3, int j = 0 is replaced by
int j = 1 ?
(A) It has no impact on the behavior of the method.
(B) It will cause the method to return a different result when the key value is not in the list.
(C) It will cause the method to return a different result when the key value is found only at the first index in the list.
(D) It will cause the method to return a different result when the key value is found only at the last index in the list.
(E) It will cause the method to throw an array index out of bounds exception.
18
Consider the following method, inCommon, which takes two integer ArrayList parameters. The method returns true if the
same integer value appears in both lists at least one time, and false otherwise.
public static boolean inCommon(ArrayList<Integer> a, ArrayList<Integer> b) {
for (int i = 0; i < a.size(); i++)
{
for (int j = 0; j < b.size(); j++) // Line 5
{
if (a.get(i).equals(b.get(j)))
{
return true;
}
}
}
return false;
}
Which of the following best explains the impact to the inCommon method when line 5 is replaced by for (int j =
b.size() - 1; j > 0; j--) ?
(A) The change has no impact on the behavior of the method.
(B) After the change, the method will never check the first element in list b.
(C) After the change, the method will never check the last element in list b.
(D) After the change, the method will never check the first and the last elements in list b.
(E) The change will cause the method to throw an indexOutof Bounds exception.
Inheritance: MCQ

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

A.The Poodle variable myDog is instantiated as a Poodle . The instance variable size is initialized to "toy" . The
instance variable name is not assiged a value.

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

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

D.A runtime error occurs because super is not used to call the no- argument Dog constructor.

E. A runtime error occurs because there is no one-argument Dog constructor.


2
Consider the following class declarations.
public class Publication
{
private String title;

public Publication()
{
title = "Generic";
}

public Publication(String t)
{
title = t;
}
}

public class Book extends Publication


{
public Book()
{
super();
}
public Book(String t)
{
super(t);
}
}

The following code segment appears in a method in another class.


Book myBook = new Book("Adventure Story"); // Line 1
Book yourBook = new Book(); // Line 2
Which of the following best describes the result of executing the code segment?
A. Object myBook is created using the one-argument Book constructor, which uses super to set myBook ’s title attribute
to "Adventure Story" . Object yourBook is created using the Book constructor, which uses super to set yourBook ’s
title attribute to an empty string.
B. Object myBook is created using the no-argument Book constructor, which uses super to set myBook ’s title attribute
to "Generic" . Object yourBook is created using super to call to the Publication no-argument constructor to set
yourBook ’s title attribute to "Generic" .
C. Object myBook is created using the one-argument Book constructor, which uses super to set myBook ’s title attribute
to "Adventure Story" . Object yourBook is created using super to call to the Publication no- argument constructor to
set yourBook ’s title attribute to "Generic" .
D. A runtime error occurs in line 1 because the one-argument Publication constructor cannot be called from the one-
argument Book constructor.
E. A runtime error occurs in line 2 because the no-argument Publication constructor cannot be called from
the no- argument Book constructor.
3
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?
A. Object tree1 is created using the DeciduousTree constructor, which uses super to set tree1 ’s treeVariety attribute to
"Maple" . Object tree2 is created using the EvergreenTree constructor, which uses super to set tree2 ’s treeVariety
attribute to "Fir" .
B. Object tree1 is created using the DeciduousTree constructor, which uses super to set tree1 ’s treeVariety attribute to
"Oak" . Object tree2 is created using the EvergreenTree constructor, which uses super to set tree2 ’s treeVariety
attribute to "Fir" .
C. Object tree1 is created using the DeciduousTree constructor, which uses super to set tree1 ’s treeVariety attribute to
"Oak" . Object tree2 is created using the EvergreenTree constructor, which uses super to set tree2 ’s treeVariety
attribute to "Oak" .
D. The code segment does not compile because the DeciduousTree and EvergreenTree constructors should not take a
parameter.
E. The code segment does not compile because the DeciduousTree and EvergreenTree constructors do not correctly call
a Tree constructor.
4
Consider the following classes.
public class Bird
{
public void sing()
{
System.out.println("Cheep");
}
}

public class Duck extends Bird


{
public void sing()
{
System.out.println("Quack");
}
}

public class Chicken extends Bird


{
// No methods defined
}

public class Rooster extends Chicken


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

A. I only
B. III only
C. I and II only
D. I and III only
E. I, II, and III
5
Consider the following class declarations.
public class Person
{
public void laugh()
{
System.out.print("Hahaha");
}
}
public class EvilPerson extends Person
{
public void laugh()
{
System.out.print("Mwahahaha");
}
}
public class Henchman extends EvilPerson
{
// No methods defined
}

The following code segment appears in a method in another class.


alice.laugh();
Under which of the following conditions will the code segment print "Mwahahaha" ?
I. When alice has been declared as type Person
II. When alice has been declared as type EvilPerson
III. When alice has been declared as type Henchman

A. II only
B. I and II only
C. I and III only
D. II and III only
E. I, II, and III
6
Consider the following class declarations.
public class ParentClass
{
public void wheelsOnTheBus()
{
System.out.println("round and round");
}
}
public class SubClass extends ParentClass
{
public void wheelsOnTheBus()
{
System.out.println("are flat");
}
}
public class SubSubClass extends ParentClass
{
public void wheelsOnTheBus()
{
// No methods defined
}
}

The following code segment appears in a method in another class.


obj.wheelsOnTheBus();
Under which of the following conditions will the code segment print "are flat" ?
I. when obj has been declared as type ParentClass
II. when obj has been declared as type SubClass
III. when obj has been declared as type SubSubClass

A. I only
B. II only
C. I and II only
D. II and III only
E. I, II, and III
7
Consider the following class declarations.
public class Range
{
private int lowValue;
public Range(int low)
{
lowValue = low;
}
public String toString()
{
return "This range starts with " + lowValue;
}
}
public class ClosedRange extends Range
{
private int highValue;
public ClosedRange(int low, int high)
{
super(low);
highValue = high;
}

public String toString()


{
return super.toString() + " and ends with " +
highValue;
}
}
A code segment appearing in a method in another class is intended to produce the following output.
This range starts with 1 and ends with 10.
Which of the following code segments will produce this output?
A. Range r1 = new Range(1);
System.out.println(r1);

B. Range r2 = new Range(1, 10);


System.out.println(r2);

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


System.out.println(r3);

D. ClosedRange r4 = new ClosedRange(10, 1);


System.out.println(r4);

E. ClosedRange r5 = new ClosedRange(10);


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

B. BallCap myHat = new BallCap("Denver", "L");


System.out.println(myHat);

C. BallCap myHat = new BallCap("L");


myHat.team = "Denver";
System.out.println(myHat);

D. BallCap myHat = new BallCap("L");


myHat.team = "Denver";
System.out.println(myHat);

E. Hat myHat = new Hat("L", "Denver");


System.out.println(myHat);
Hat myHat = new Hat("L");
myHat.team = "Denver";
System.out.println(myHat);
9
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" ?
A Parent a = new Parent();
a.first();

B Child b = new Child();


b.first();

C Child c = new Child();


c.second();

D Grandchild d = new Grandchild();


d.first();

E Grandchild e = new Grandchild();


e.second();
10
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?

A Line 2 causes a compile-time error because the variable tool1 is declared as type MultiTool but is instantiated as a
DeluxeMultiTool.

B Line 3 causes a compile-time error because the variable tool2 is declared as type MultiTool and is instantiated as
a DeluxeMultiTool.

C In line 4, tool2 cannot be added to the ArrayList because it was instantiated as a DeluxeMultiTool .

D In line 5, tool2 cannot be added to the ArrayList because it was declared to be of type DeluxeMultiTool .

E Line 8 causes a compile-time error because the getCompass method is not defined for objects of type MultiTool.
11
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?
A Line 1 will cause an error because the type used to declare arr and the type used to instantiate arr
are different.

B Line 3 will cause an error because the type used to declare t2 and the type used to instantiate t2 are
different.

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

D Line 6 will cause an error because the types of arr[1] and t2 are different.

E Line 7 will cause an error because the types of arr[2] and t3 are different.
12
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?
A Line 3 causes a compile-time error because the Refrigerator class is missing the display() method.

B Line 6 causes a compile-time error because the variable a1 is incorrectly instantiated.

C Line 7 causes a compile-time error because the variable a2 is incorrectly instantiated.

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

E Line 9 causes a compile-time error because the parameter a2 in the call displayFeatures(a2) has the incorrect
data type.
13
Consider the following class definitions.
public class First
{
public void output1()
{
output2();
}
public void output2()
{
output3();
}
public void output3()
{
System.out.print("First");
}
}
public class Second extends First
{
public void output()
{
output1();
output2();
output3();
}
}
public class Third extends Second
{
public void output3()
{
System.out.print("Third");
}
}
The following code segment appears in a class other than First, Second, or Third.
First sec = new Second(); // Line 1
Second thr = new Third(); // Line 2
sec.output(); // Line 3
thr.output(); // Line 4
Which of the following best explains why the code segment will not compile?
A Line 3 causes a compile-time error because the variable sec should be declared as type Second .

B Line 4 causes a compile-time error because the variable thr should be declared as type Third .

C Line 3 causes a compile-time error because the Second class is missing the output1 method.

D Line 3 causes a compile-time error because the Second class is missing the output2 method.

E Line 4 causes a compile-time error because the Third class is missing the output method.
14
Consider the following class definitions.
public class Person
{
private String firstName;
private String lastName;
public Person(String pFirstName, String pLastName)
{
firstName = pFirstName;
lastName = pLastName;
}

public void personInfo()


{
System.out.println("My name is " + firstName
+ " " + lastName);
}

pubic class Teacher extends Person


{
private String school;
private String subject;
public Teacher(String tFN, String tLN, String tSchool,
String tSubject)
{
super(tFN, tLN);
school = tSchool;
subject = tSubject;
}
public void teacherInfo()
{
personInfo();
System.out.println("I teach " + subject + " at "
+ school);
}
}
The following code segment appears in a class other than Person or Teacher.
Person teach = new Teacher("Henry", "Lowe", "PS 150", "English");
teach.teacherInfo();
Which of the following best explains why the code segment will not compile?
A The call to personInfo(); in the teacherInfo method should be this.personInfo(); because personInfo is a method in
the Person class.
B The personInfo method should be moved to the Teacher class because personInfo is a method only in the Person
class.
C The teacherInfo method should be moved to the Person class because teacherInfo is a method in the Teacher class.
D The variable teach should be declared as a Teacher data type because teacherInfo is a method in the Teacher class.
E The variable teach should be instantiated as a Person object because teach has been declared as type Person.
15
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?
A The variable thing should be declared as a Bclass data type because thing is instantiated as a Bclass object.
B The variable thing should be instantiated as an Aclass object because methodY is overridden in Bclass.
C The method methodX should be removed from the Aclass definition because methodX is overridden in Bclass.
D The method methodY should be removed from the Aclass definition because methodY is overridden in Bclass.
E The method methodZ should be overridden in the Bclass definition because methodZ appears only in Aclass.
16
Consider the following class definitions.
public class Vehicle
{
private int numOfWheels;
public Vehicle(int nNumOfWheels)
{
numOfWheels = nNumOfWheels;
}
public String toString()
{
return "Number of Wheels: " + numOfWheels;
}
}
public class Motorized extends Vehicle
{
private int maxSpeed;
public Motorized(int nNumOfWheels, nMaxSpeed)
{
super(nNumOfWheels);
maxSpeed = nMaxSpeed;
}
public String toString()
{
String s = super.toString() + " Max Speed: ";
if (maxSpeed <= 10)
{
s += "Slow";
}
else if (maxSpeed > 10 && maxSpeed <= 100)
{
s += "Fast";
} else
{
s += "Super Speedy";
}
return s;
}
}
Which of the following code segments, when executed in a class other than Vehicle or Motorized, will display Number
of Wheels: 4 Max Speed: Fast ?
A Vehicle obj = new Vehicle(55);
System.out.println(obj);
B Vehicle obj = new Vehicle(55);
System.out.println(toString(obj));
C Motorized obj = new Motorized(55);
System.out.println(obj);
D Vehicle obj = new Motorized(4, 55);
System.out.println(obj);
E Motorized obj = new Motorized(4, 55);
System.out.println(toString(obj));
17
Consider the following class definition.
public class Silly
{
private int var1;
private String var2;
public Silly(int v1, String v2)
{
var1 = v1;
var2 = v2;
}
public boolean equals(Object other)
{
if (other == null)
{
return false;
}
Silly s = (Silly) other;
return (var1 == s.var1 && var1 == var2.length()
&& var2.length() == s.var2.length());
}
}
The following code segment appears in a class other than Silly.
Silly s1 = new Silly(3, "abcd");
Silly s2 = new Silly(3, "abcd");
Silly s3 = new Silly(5, "vwxyz");
Silly s4 = new Silly(5, "aaaaa");
Silly s5 = new Silly(5, "efg");
Which of the following Boolean expressions will evaluate to true ?
A s1.equals(s2)

B s2.equals(s3)

C s3.equals(s4)

D s4.equals(s5)

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

B II only

C III only

D I and II

E I and III
19

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?
A. Daryl
B. Daryl 555-1234
C. Alice 555-1234
Daryl
D. Alice 555-1234
Daryl 555-1234
E. this
20

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?


A. e
B. default
C. [email protected]
D. [email protected]
E. Nothing is printed because the class will not compile.
21
Consider the following class definitions.
public class Animal
{
public void eat()
{ /* implementation not shown */ }
// constructors and other methods not shown
}
public class Tiger extends Animal
{
public void roar()
{ /* implementation not shown */ }
// constructors and other methods not shown
}
Assume that the following declaration appears in a client class.
Animal a = new Tiger();
Which of the following statements would compile without error?
I. a.eat();
II. a.roar();
III. ((Tiger) a).roar();
(A) I only
(B) II only
(C) III only
(D) I and III only
(E) I, II, and III
22
Consider the following class declarations.
public class Base
{
private int myVal;
public Base()
{
myVal = 0;
}
public Base(int x)
{
myVal = x;
}
}
public class Sub extends Base
{
public Sub()
{
super(0);
}
}
Which of the following statements will NOT compile?
(A) Base b1 = new Base();
(B) Base b2 = new Base(5);
(C) Base s1 = new Sub();
(D) Sub s2 = new Sub();
(E) Sub s3 = new Sub(5);

23
Assume that class Vehicle contains the following method.
public void setPrice(double price)
{ /* implementation not shown */ }
Also assume that class Car extends Vehicle and contains the following method.
public void setPrice(double price)
{ /* implementation not shown */ }
Assume Vehicle v is initialized as follows.
Vehicle v = new Car();
v.setPrice(1000.0);
Which of the following is true?
(A) The code above will cause a compile-time error, because a subclass cannot have a method with the same name and
the same signature as its superclass.
(B) The code above will cause a run-time error, because a subclass cannot have a method with the same name and the
same signature as its superclass.
(C) The code above will cause a compile-time error because of type mismatch.
(D) The code v.setPrice(1000.0); will cause the setPrice method of the Car class to be called.
(E) The code v.setPrice(1000.0); will cause the setPrice method of the Vehicle class to be called.
24
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.

25
When designing a class hierarchy, which of the following should be true of a superclass?
(A) A superclass should contain the data and functionality that are common to all subclasses that inherit from the
superclass.
(B) A superclass should be the largest, most complex class from which all other subclasses are derived.
(C) A superclass should contain the data and functionality that are only required for the most complex class.
(D) A superclass should have public data in order to provide access for the entire class hierarchy.
(E) A superclass should contain the most specific details of the class hierarchy.
26
Consider the following two classes.
public class Dog
{
public void act()
{
System.out.println("run");
eat();
}
public void eat()
{
System.out.println("eat");
}
}
public class UnderDog extends Dog
{
public void act()
{
super.act();
System.out.println("sleep");
}
public void eat()
{
super.eat();
System.out.println("bark");
}
}

Assume that the following declaration appears in a class other than Dog.
Dog fido = new UnderDog ( ) ;
What is printed as a result of the call fido.act() ?
(A) run eat
(B) run eat sleep
(C) run eat sleep bark
(D) run eat bark sleep
(E) Nothing is printed due to infinite recursion.
27
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 the Computer object myPhone.
28
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.
29
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.
30
Consider the following declarations.
public class Example0
{
public void doNothing(Examplel b, Example2 c)
{…}
}
public class Examplel extends Example0
{
}
public class Example2 extends Examplel
{
}
The following initializations appear in a different class.
Example0 e0 = new Example0();
Examplel el = new Examplel();
Example2 e2 = new Example2();
Which of the following is a correct call to doNothing?
(A) e0.doNothing(e0, e0);
(B) e1.doNothing(el, el);
(C) el.doNothing(e2, el);
(D) e2.doNothing(e0, e0);
(E) e2.doNothing(e2, e2);
31
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.
32
Consider the following classes.
public class Base
{
public Base()
{
System.out.print("Base" + " ");
}
}
public class Derived extends Base
{
public Derived()
{
System.out.print("Derived" + " ");
}
}
Assume that the following statement appears in another class.
Derived d1 = new Derived();
What is printed as a result of executing the statement?
(A) Nothing is printed because the statement is a variable declaration.
(B) Base
(C) Derived
(D) Base Derived
(E) Derived Base
33
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.
34
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

35
A car dealership needs a program to store information about the cars for sale. For each car, they want to keep track of the
following information: number of doors (2 or 4), whether the car has air conditioning, and its average number of miles per
gallon. Which of the following is the best object-oriented program design?
(A) Use one class, Car, with three instance variables: int numDoors, boolean hasAir, and double milesPerGallon.
(B) Use four unrelated classes: Car, Doors, AirConditioning, and MilesPerGallon.
(C) Use a class Car with three subclasses: Doors, AirConditioning, and MilesPerGallon.
(D) Use a class Car, with a subclass Doors, with a subclass AirConditioning, with a subclass MilesPerGallon.
(E) Use three classes: Doors, AirConditioning, and MilesPerGallon, each with a subclass Car.
36
Consider the following class definitions.
public class A
{
private int al;
public void methodA()
{
methodB(); // Statement I
}
}
public class B extends A
{
public void methodB()
{
methodA(); // Statement II
al = 0; // Statement III
}
}
Which of the labeled statements in the methods shown above will cause a compile-time error?
(A) I only
(B) III only
(C) I and II
(D) I and III
(E) II and III
37
Consider the following class declarations.
public class A
{
private int x;
public A()
{ x = 0; }
public A(int y)
{ x = y; }
/* There may be instance variables, constructors, and methods that are not
shown.*/
}
public class B extends A
{
private int y;
public B()
{
/* missing code */
}
/* There may be instance variables, constructors, and methods that are not
shown.*/
}
Which of the following can be used to replace /* missing code */ so that the statement
B temp = new B();
will construct an object of type B and initialize both x and y with 0 ?
I. y = 0
II. super (0);
y = 0;
III. x = 0;
y = 0;
(A) I only
(B) II only
(C) I and II only
(D) II and III only
(E) I, II, and III
38
Consider the following class definitions.
public class Data
{
private int x;
public void setX(int n)
{
x = n;
}
// ... other methods not shown
}
public class EnhancedData extends Data
{
private int y;
public void setY(int n)
{
y = n:
}
// ... other methods not shown
}
Assume that the following declaration appears in a client program.
EnhancedData item = new EnhancedData();
Which of the following statements would be valid?
I. item.y = 16;
II. item.setY(16);
III. item.setX(25);
(A) I only
(B) II only
(C) I and II only
(D) II and III only
(E) I, II, and III
39
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.
Recursion: MCQ
1

Consider the following recursive method, which is intended to display the binary equivalent of a decimal
number. For example, toBinary(100) should display 1100100.

public static void toBinary(int num)


{
if (num < 2)
{
System.out.print(num);
}
else
{
/* missing code */
}

Which of the following can replace /* missing code */ so that toBinary works as intended?
A
System.out.print(num % 2);
toBinary(num / 2);

B
System.out.print(num / 2);
toBinary(num % 2);

C
toBinary(num % 2);
System.out.print(num / 2);

D
toBinary(num / 2);
System.out.print(num % 2);

E
toBinary(num / 2);
System.out.print(num / 2);
2

Consider the following recursive method, which is intended to return a String with any
consecutive duplicate characters removed. For example, removeDupChars("aabcccd") returns
"abcd".

public static String removeDupChars(String str)


{
if (str == null || str.length() <= 1)
{
return str;
}
else if (str.substring(0, 1).equals(str.substring(1, 2)))
{
return removeDupChars(str.substring(1));
}
else
{
/* missing code */
}

Which of the following can replace /* missing code */ so that removeDupChars works as intended?

A. return removeDupChars(str.substring(2));
B. return removeDupChars(str.substring(1)) + str.substring(0, 1);
C. return removeDupChars(str.substring(2)) + str.substring(1, 2);
D. return str.substring(0, 1) + removeDupChars(str.substring(1));
E. return str.substring(1, 2) + removeDupChars(str.substring(2));
3

Consider the following method, which is intended to return the sum of all the even digits in its
parameter num. For example, sumEvens(15555234) should return 6, the sum of 2 and 4.

/** Precondition: num >= 0 */

public static int sumEvens(int num)


{
if (num < 10 && num % 2 == 0)
{
return num;
}
else if (num < 10)
{
return 0;
}
else if (num >= 10 && num % 2 == 0)
{
/* missing statement */
}
else
{
return sumEvens(num / 10);
}

Which of the following can be used as a replacement for /* missing statement */ so that the
sumEvens method works as intended?

A. return sumEvens(num % 10);


B. return sumEvens(num / 10);
C. return num % 10 + sumEvens(num % 10);
D. return num % 10 + sumEvens(num / 10);
E. return num / 10 + sumEvens(num % 10);
4
Consider the following method.
/** Precondition: n > 0 */

public static void mystery(int n)


{
System.out.print(n + " ");
if (n > 1)
{
mystery(n - 1);
}

Which of the following best describes the output produced by the method call mystery(val) ?
A. All integers from 1 to val, separated by spaces
B. All integers from val to 1, separated by spaces
C. The digits of val in their original order, separated by spaces
D. The digits of val in reverse order, separated by spaces
E. The last digit of val, then a space, then the first digit of
val

Consider the following recursive method.

public static String doSomething(String str)


{
if (str.length() < 1)
{
return "";
}
else
{
return str.substring(0, 1) +
doSomething(str.substring(1));
}

Which of the following best describes the result of the call doSomething(myString) ?

A. The method call returns a String containing the contents of myString unchanged.
B. The method call returns a String containing the contents of myString with the order of the
characters reversed from their order in myString.
C. The method call returns a String containing all but the first character of myString.
D. The method call returns a String containing only the first and second characters of myString.
E. The method call returns a String containing only the first and last characters of myString.
6

Consider the following recursive method.

/** Precondition: n > 0 */

public static int calc(int n)


{
if (n <= 9)
{
return n;
}
else
{
return calc(n / 10);
}

}
Which of the following best describes the value returned by the method call calc(num) ?

A. The int value 9.


B. The leftmost digit of num
C. The rightmost digit of num
D. The number of digits in num
E. The result of the integer division of num by 10
Sorting and Searching: MCQ
1
Consider the following correct implementation of the insertion sort algorithm.

public static void insertionSort(int[] elements)


{
for (int j = 1; j < elements.length; j++)
{
int temp = elements[j];
int possibleIndex = j;
while (possibleIndex > 0 && temp < elements[possibleIndex - 1])
{
elements[possibleIndex] = elements[possibleIndex - 1];
possibleIndex--; // line 10
}
elements[possibleIndex] = temp;
}
}

The following declaration and method call appear in a method in the same class as insertionSort.

int[] arr = {10, 8, 3, 4};


insertionSort(arr);

How many times is the statement possibleIndex--; in line 10 of the method executed as a result of the call to
insertionSort ?
A. 0
B. 1
C. 4
D. 5
E. 6
2
Consider the following correct implementation of the insertion sort algorithm.
public static void insertionSort(int[] elements)
{
for (int j = 1; j < elements.length; j++)
{
int temp = elements[j];
int possibleIndex = j;
while (possibleIndex > 0 && temp < elements[possibleIndex - 1])
{
elements[possibleIndex] = elements[possibleIndex - 1];
possibleIndex--;
}
elements[possibleIndex] = temp; // line 12
}
}

The following declaration and method call appear in a method in the same class as insertionSort.
int[] nums = {8, 7, 5, 4, 2, 1};
insertionSort(nums);

How many times is the statement elements[possibleIndex] = temp; in line 12 of the method executed as a
result of the call to insertionSort ?
A. 3
B. 4
C. 5
D. 6
E. 7
3
Consider the following correct implementation of the selection sort algorithm.

public static void selectionSort(int[] elements)


{
for (int j = 0; j < elements.length - 1; j++)
{
int minIndex = j;
for (int k = j + 1; k < elements.length; k++)
{
if (elements[k] < elements[minIndex])
{
minIndex = k;
}
}

if (j != minIndex)
{
int temp = elements[j];
elements[j] = elements[minIndex];
elements[minIndex] = temp; // line 19
}
}

The following declaration and method call appear in a method in the same class as selectionSort.

int[] arr = {30, 40, 10, 50, 20};


selectionSort(arr);

How many times is the statement elements[minIndex] = temp; in line 19 of the method executed as a result
of the call to selectionSort ?

A. 1
B. 2
C. 3
D. 4
E. 5
4

Consider the following mergeSortHelper method, which is part of an algorithm to recursively


sort an array of integers.

/** Precondition: (arr.length == 0 or 0 <= from <= to <=


* arr.length)
* arr.length == temp.length
*/

public static void mergeSortHelper(int[] arr, int from, int to, int[]
temp)
{
if (from < to)
{
int middle = (from + to) / 2;
mergeSortHelper(arr, from, middle, temp);
mergeSortHelper(arr, middle + 1, to, temp);
merge(arr, from, middle, to, temp);
}
}

The merge method is used to merge two halves of an array (arr[from] through arr[middle],
inclusive, and arr[middle + 1] through arr[to], inclusive) when each half has already been sorted
into ascending order. For example, consider the array arr1, which contains the values {1, 3, 5, 7,
2, 4, 6, 8}. The lower half of arr1 is sorted in ascending order (elements arr1[0] through arr1[3],
or {1, 3, 5, 7}), as is the upper half of arr1 (elements arr1[4] through arr1[7], or {2, 4, 6, 8}).
The array will contain the values {1, 2, 3, 4, 5, 6, 7, 8} after the method call merge(arr1, 0, 3, 7,
temp). The array temp is a temporary array declared in the calling program.

Consider the following code segment, which appears in a method in the same class as
mergeSortHelper and merge.

int[] arr1 = {9, 1, 3, 5, 4};

int[] temp = new int[arr1.length];

mergeSortHelper(arr1, 0, arr1.length - 1, temp);

Which of the following represents the arrays merged the first time the merge method is executed
as a result of the code segment above?

A. {9} and {1} are merged to form {1, 9}.


B. {1, 9} and {3} are merged to form {1, 3, 9}.
C. {1, 9} and {5, 4} are merged to form {1, 4, 5, 9}.
D. {1, 3, 9} and {5} are merged to form {1, 3, 5, 9}.
E. {1, 3, 9} and {4, 5} are merged to form {1, 3, 4, 5, 9}.
5

Consider the following method, which implements a recursive binary search.

/** Returns an index in arr where target appears, if target appears


* in arr between arr[low] and arr[high], inclusive;
* otherwise, returns -1.
* Precondition: arr is sorted in ascending order.
* low >= 0, high < arr.length, arr.length > 0
*/

public static int binarySearch(int[] arr, int low, int high, int target)
{

if (low > high)


{
return -1;
}

int middle = (low + high) / 2;

if (target == arr[middle])
{
return middle;
}
else if (target < arr[middle])
{
return binarySearch(arr, low, middle - 1, target);
}
else
{
return binarySearch(arr, middle + 1, high, target);
}

The following code segment appears in a method in the same class as binarySearch.

int[] arr = {2, 3, 12, 34, 54};


int result = binarySearch(arr, 0, arr.length - 1, 5);

If the first call to binarySearch is the call in the code segment above, with low = 0 and high = 4,
which, if any, of the following shows the values of low and high when binarySearch is called for
the third time?

A. low = 0, high = 1
B. low = 0, high = 2
C. low = 1, high = 1
D. low = 2, high = 1
E. The method returns to the calling code segment before the third call to binarySearch.
6

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 target = 10;


int[] arrWithDups = {2, 3, 7, 8, 10, 10, 10, 20};
int arrIndex = bSearch(arrWithDups, 0, arrWithDups.length - 1, target);

What is the value of arrIndex after the code segment has been executed?
A. 4
B. 5
C. 6
D. 7
E. 10
7

Consider the following method, which implements a recursive binary search.

/** Returns an index in theList where target appears,


* if target appears in theList between the elements at indices
* low and high, inclusive; otherwise returns -1.
* Precondition: theList is sorted in ascending order.
* low >= 0, high < theList.size(), theList.size() > 0
*/

public static int binarySearch(ArrayList<Integer> theList, int low,


int high, int target)
{
if (low > high)
{
return -1;
}

int middle = (low + high) / 2;


if (target == theList.get(middle))
{
return middle;
}
else if (target < theList.get(middle))
{
return binarySearch(theList, low, middle - 1, target);
}
else
{
return binarySearch(theList, middle + 1, high, target);
}

The following code segment appears in a method in the same class as binarySearch.

ArrayList<Integer> theList = new ArrayList<Integer>();


for (int k = 10; k < 65; k = k + 5)
{
theList.add(k);
}
int result = binarySearch(theList, 0, theList.size() - 1, 45);

Including the call to binarySearch in the last statement of the given code segment, how many
times will binarySearch be called before a value is returned?
A. 1
B. 2
C. 3
D. 4
E. 8
8

Consider the following method, which implements a recursive binary search.

/** Returns an index in arr where the value str appears if str 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(String[] arr, int left, int right, String str)
{

if (right >= left)


{
int mid = (left + right) / 2;
if (arr[mid].equals(str))
{
return mid;
}
else if (arr[mid].compareTo(str) > 0)
{
return bSearch(arr, left, mid - 1, str);
}
else
{
System.out.println("right");
return bSearch(arr, mid + 1, right, str);
}
}
return -1;

}
The following code segment appears in a method in the same class as bSearch.

String[] words = {"arc", "bat", "cat", "dog", "egg", "fit", "gap",


"hat"};

int index = bSearch(words, 0, words.length - 1, "hat");

How many times will "right" be printed when the code segment is executed?
A. 1
B. 2
C. 3
D. 7
E. 8
9

Consider the following method, which implements a recursive binary search.

/** Returns an index in nums where target appears if target appears in nums between
* nums[lo] and nums[hi], inclusive; otherwise, returns -1.
* Precondition: nums is sorted in ascending order.
* low >= 0, high < nums.length, nums.length > 0
*/
public static int bSearch(int[] nums, int low, int high, int target)
{

if (high >= low)


{
int mid = (low + high) / 2;
if (nums[mid] == target)
{
return mid;
}
if (nums[mid] > target)
{
return bSearch(nums, low, mid - 1, target);
}
else
{
return bSearch(nums, mid + 1, high, target);
}
}
return -1;

The following code segment appears in a method in the same class as bSearch.

int target = 3;
int[] nums = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int targetIndex = bSearch(nums, 0, nums.length - 1, target);

How many times will bSearch be called as a result of executing the code segment above?

A. 1
B. 2
C. 3
D. 4
E. 5
10
Consider the following correct implementation of the insertion sort algorithm. The insertionSort method
correctly sorts the elements of ArrayList data into increasing order.
public static void insertionsort(ArrayList<Integer> data)
{
for (int j = 1; j < data.size(); j++)
{
int v = data.get(j);
int k = j;
while (k > 0 && v < data.get(k - 1))
{
data.set(k, data.get(k - 1)); /* Statement 1 */
k--;
}
data.set(k, v); /* Statement 2 */
/* End of outer loop */
}
}
Assume that insertionSort has been called with an ArrayList parameter that has been initialized with the
following integer objects.
[5, 2, 4, 1, 3, 6]
What will the contents of data be after three passes of the outside loop (i.e., when j == 3 at the point
indicated by /* End of outer loop */) ?
(A) [1, 2, 3, 4, 5, 6]
(B) [1, 2, 3, 5, 4, 6]
(C) [1, 2, 4, 5, 3, 6]
(D) [2, 4, 5, 1, 3, 6]
(E) [5, 2, 1, 3, 4, 6]
11
Consider the following correct implementation of the insertion sort algorithm. The insertionsort method
correctly sorts the elements of ArrayList data into increasing order.
public static void insertionsort(ArrayList<Integer> data)
{
for (int j = 1; j < data.size(); j++)
{
int v = data.get(j);
int k = j;
while (k > 0 && v < data.get(k - 1))
{
data.set(k, data.get(k - 1)); /* Statement 1 */
k--;
}
data.set(k, v); /* Statement 2 */
/* End of outer loop */
}
}
Assume that insertionsort is called with an ArrayList parameter that has been initialized with the following
integer objects.
[1, 2, 3, 4, 5, 6 ]
How many times will the statements indicated by /* Statement 1 */ and /* Statement 2 */ execute?

(A)
Statement 1 Statement 2

0 0

(B)
Statement 1 Statement 2

0 5

(C)
Statement 1 Statement 2

0 6

(D)
Statement 1 Statement 2

5 5

(E)
Statement 1 Statement 2

6 6
12
Consider the following correct implementation of the selection sort algorithm.
public static void selectionSort(int[] elements)
{
for (int j = 0; j < elements.length - 1; j++)
{
int minindex = j;
for (int k = j + 1; k < elements.length; k++)
{
if (elements[k] < elements[minindex])
{
minindex = k;
}
}
if (j != minindex)
{
int temp = elements[j];
elements[j] = elements[minindex];
elements[minindex] = temp; // Line 19
}
}
}
The following declaration and method call appear in a method in the same class as selectionsort.
int[ ] arr = {9, 8, 7, 6, 5};
selectionSort(arr);
How many times is the statement elements [minindex ] = temp; in line 19 of the method
executed as a result of the call to selectionSort ?
(A) 1
(B) 2
(C) 3
(D) 4
(E) 5

13
Consider the following code segment from an insertion sort program.
for (int j = 1; j < arr.length; j++)
{
int insertitem = arr[j];
int k = j - 1;
while (k >= 0 && insertitem < arr[k])
{
arr[k + 1] = arr[k];
k--;
}
arr[k + 1] = insertitem;
/* end of for loop */
}
Assume that array arr has been defined and initialized with the values {5,4,3,2,1}. What are the
values in array arr after two passes of the for loop (i.e., when j = 2 at the point indicated by / * end of for
loop */) ?
(A) {2, 3, 4, 5, 1}
(B) {3, 2, 1, 4, 5}
(C) {3, 4, 5, 2, 1}
(D) {3, 5, 2, 3, 1}
(E) {5, 3, 4, 2, 1}
14
The following sort method correctly sorts the integers in elements into ascending order
Line 1: public static void sort (int [] elements)
Line 2: {
Line 3: for (int j = 0; j < elements. length - 1; j+ + )
Line 4: {
Line 5. int index = j ;
Line 6:
Line 7: for (int k = j + 1; k < elements. length; k+ + )
Line 8: {
Line 9: if (elements [k] < elements [index])
Line 10: {
Line 11: index = k;
Line 12: }
Line 13: }
Line 14:
Line 15: int temp = elements [ j ];
Line 16: elements [ j ] = elements [index];
Line 17: elements [index] = temp;
Line 18: }
Line 19: }
Which of the following changes to the sort method would correctly sort the integers in elements into
descending order?

I. Replace line 9 with:


Line 9: if (elements [k] > elements [index])

II. Replace lines 15-17 with:


Line 15: int temp = elements [index];
Line 16: elements [index] = elements [ j ];
Line 17: elements [ j ] = temp;

III. Replace line 3 with:


Line3: for (int j = elements.length - 1; j > 0; j —)
and replace line 7 with:
Line 7: for (int k = 0; k < j ; k+ + )

(A) I only
(B) II only
(C) I and II only
(D) I and III only
(E) I, II and III
15
Consider the following correct implementation of the insertion sort algorithm.
public static void insertionSort(int[] elements)
{
for (int j= 1; j < elements.length; j++)
{
int temp = elements [j];
int possibleIndex = j;

while (possibleIndex > 0 && temp < elements [possibleIndex - 1])


{
elements [possibleIndex] = elements [possibleIndex - 1];
possibleIndex--; // Line 10
}
elements [possibleIndex] = temp;
}
}

The following declaration and method call appear in a method in the same class as insertionSort.

int[] arr = {4, 12, 4, 7, 19, 6};


insertionSort(arr);

How many times is the statement possibleIndex--; in line 10 of the method executed as a result of the
call to insertionSort?

(A) 2
(B) 3
(C) 4
(D) 5
(E) 6
16
Consider the following correct implementation of the selection sort algorithm.
public static void selectionSort(int[] elements)
{

for(int j = 0; j < elements.length – 1; j++)


{
int minIndex= j;
for (int k=j+1; k < elements.length;k++)
{
if (elements[k] < elements[minIndex])
{
minIndex=k; // Line 11
}
}
if (j!= minIndex)
{
int temp = elements[j];
elements[j]= elements[minIndex];
elements[minIndex]=temp;
}
}
}

The following declaration and method call appear in the same class as selectionsort.

int[] vals ={5, 10, 2, 1,12};


selectionSort(vals);

How many times is the statement minIndex = k; in line 11 of the method executed as a result of the call
to selectionsort?
(A) 0
(B) 1
(C) 2
(D) 3
(E) 4

17
Consider the following two data structures for storing several million words.

I. An array of words, not in any particular order

II. An array of words, sorted in alphabetical order

Which of the following statements most accurately describes the time needed for operations on these data
structures?

(A) Inserting a word is faster in II than in I.


(B) Finding a given word is faster in I than in II.
(C) Finding a given word is faster in II than in I.
(D) Finding the longest word is faster in II than in I.
(E) Finding the first word in alphabetical order is faster in I than in II.
18
Consider the static method selectSort shown below. Method selectSort is intended to sort an array into
increasing order; however, it does not always work as intended.

// precondition: numbers.length > 0


// postcondition: numbers is sorted in increasing order
public static void selectsort (int [] numbers)
{
int temp;
Line 1: for (int j = 0;j < numbers.length - 1; j++)
{
Line 2: int pos = 0;
Line 3: for (int k = j + 1; k < numbers.length; k++)
{
Line 4: if (numbers [k] < numbers [pos])
{
Line 5: pos = k;
}
}
temp = numbers [j];
numbers [j] = numbers [pos];
numbers [pos] = temp;
}
}

Which of the following changes should be made so that selectSort will work as intended?

(A) Line 1 should be changed to


for (int j = 0; j < numbers.length - 2; j++)

(B) Line 2 should be changed to


int pos = j;

(C) Line 3 should be changed to


for (int k = 0; k < numbers.length; k++)

(D) Line 4 should be changed to


If( numbers[k] > numbers[pos] )

(E) Line 5 should be changed to


k = pos;
19
Consider the following method.

public static void sort (String [] arr)


{
for (int pass = arr.length - 1; pass >= 1; pass--)
{
String large = arr[0];
int index = 0;
for (int k = 0; k <= pass; k++)
{
if ((arr[k] .compareTo (large)) > 0)
{
large = arr[k];
index = k;
}
}
arr [index] = arr [pass];
arr [pass] = large;
}
}
Assume arr is the following array.
"Ann" "Mike" "Walt" "Lisa" "Shari" "Jose" "Mary" "Bill"

What is the intermediate value of arr after two iterations of the outer for loop in the call sort (arr)?

(A)
"Ann" "Mike" "Walt" "Lisa" "Shari" "Jose" "Mary" "Bill"

(B)
"Ann" "Mike" "Lisa" "Shari" "Jose" "Mary" "Bill" "Walt"

(C)
"Ann" "Bill" "Jose" "Lisa" "Mary" "Mike" "Shari" "Walt"

(D)
"Ann" "Mike" "Bill" "Lisa" "Mary" "Jose" "Shari" "Walt"

(E)
"Walt" "Shari" "Ann" "Lisa" "Mike" "Jose" "Mary" "Bill"
20
Directions: Select the choice that best fits each statement. The following question(s) refer to the following
information.
Consider the following sort method. This method correctly sorts the elements of array data into increasing
order.
public static void sort(int[]data)
{
for (int j=0; j<data.length – 1; j ++)
{
int m = j;
for (int k = j+1;k < data.length; k ++)
{
if (data[k] < data[m]) /*Compare values */
{
m = k;
}
}
int temp = data[m]; /*Assign to temp */
data[m] = data[j];
data[j]=temp;
/* End of outer loop */
}
}
Assume that sort is called with the array {6,3,2,5,4,1}.What will the value of data be after three passes of the
outer loop(i.e.,when j=2 at the point indicated by /* End of outer loop*/)?

(A) {1, 2, 3, 4, 5, 6}
(B) {1, 2, 3, 5, 4, 6}
(C) {1, 2, 3, 6, 5, 4}
(D) {1, 3, 2, 4, 5, 6}
(E) {1, 3, 2, 5, 4, 6}
21
Directions: Select the choice that best fits each statement. The following question(s) refer to the following
information.
Consider the following sort method. This method correctly sorts the elements of array data into increasing
order.
public static void sort(int[] data)
{
for (int j = 0; j < data.length - 1; j++)
{
int m = j;
for (int k = j + 1; k < data.length; k++)
{
if (data [k] < data [m] ) /* Compare values */
{
m = k;
}
}
int temp = data[m] ; /* Assign to temp */
data[m] = data[j];
data[j] = temp;
/ * End of outer loop * /
}
}
Assume that sort is called with the array {1,2,3,4,5,6}. How many times will the expression indicated by /*
Compare values */ and the statement indicated by /* Assign to temp */ execute?
(A) Compare values / Assign to temp
15/0
(B) Compare values / Assign to temp
15/5
(C) Compare values / Assign to temp
15/6
(D) Compare values / Assign to temp
21/5
(E) Compare values / Assign to temp
21/6
22
The following incomplete method is intended to sort its array parameter arr in increasing order.
//postcondition: arr is sorted in increasing order
public static void sortArray(int[] arr)
{
int j, k;
for (j = arr.length - 1; j > 0; j--)
{
int pos = j;
for ( /* missing code */ )
{
if (arr(k] > arr(pos])
{
pos = k;
}
}
swap(arr, j, pos);
}
}

Assume the swap(arr, j, pos) exchanges the values of arr[i] and arr[j]. Which of the
following could be used to replace /* missing code */ so that executing the code segment sorts the
values in array arr?

(A) k = j - 1; k > 0; k--


(B) k = j - 1; k >= 0; k--
(C) k = 1; k < arr.length; k++
(D) k = 1; k > arr.length; k++
(E) k = 0; k <= arr.length; k++

You might also like