Csa AP Classroom Mcq
Csa AP Classroom 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);
3.
Consider the following expression.
(3 + 4 == 5) != (3 + 4 >= 5)
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);
}
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 (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.
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;
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.
Which of the following should replace /* missing loop header */ so that the code segment will work as
intended?
12
Consider the following code segment.
int a = 1;
String result = "";
}
System.out.println(result);
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;
}
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
Code Segment II
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.
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?
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++;
}
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.
Which of the following can be used to replace /* missing loop header */ so that the code segment will work as
intended?
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 */
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?
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.
if (arr[k].length() >= 3)
{
count++;
}
}
return count;
}
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. 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.
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.
Which of the following best identifies why the code segment does not work as intended?
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]);
}
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 ?
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.
Which of the following can replace /* missing loop header */ so that the code segment works as intended?
Which of the following can be used to replace /* missing loop header */ so that the code segment works as intended?
12
Consider the following method, which is intended to return the index of the first negative integer in a given array of
integers.
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?
{{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.
Which of the following initializer lists could replace /* missing code */ so that the code segment will work
as intended?
Which of the following can replace /* missing expression */ so that the code segment works as intended?
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.
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.
The following code segment appears in another method in the same class.
System.out.println(mystery("Mississippi", "si"));
3
Consider the following code segment.
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.
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
/* 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?
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 */
public Thing(String s)
{ /* implementation not shown */ }
}
4
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;
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
/* 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".
B private Person(String n)
{
name = n;
}
C public Person()
{
name = n;
}
D public Person(String n)
{
name = n;
}
Which of the following best describes the reason this code segment will not compile?
public getName()
{
return name;
}
}
Which choice correctly explains why this class definition fails to compile?
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.
Which of the following statements best explains why the getH method does not work as intended?
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.
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.
Which of the following changes should be made so that the levelUp method works as intended?
Which of the following changes can be made so that the reset method works as intended?
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;
}
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;
}
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
Which of the following best describes the sell method’s level of access to the numOunces and numSold
variables?
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.
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.
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
}
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.
The ClassP constructor is intended to initialize the str instance variable to the value of the formal parameter
newStr. Which of the following statements best describes why the ClassP constructor does not work as
intended?
}
}
The 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.
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.
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));
}
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.
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.
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.
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.
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.
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.
A. 0123
B. 1234
C. 02
D. 13
E. 24
8
Consider the following code segment.
A. []
B. [new, pet]
C. [open, pet]
D. [new, open, pet]
E. [mat, new, open, pet]
9
Consider the following 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.
The method does not always work as intended. For which of the following inputs does the method NOT return the correct
value?
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.
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.
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.
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?
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;
}
}
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.
public Publication()
{
title = "Generic";
}
public Publication(String t)
{
title = t;
}
}
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
}
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
}
}
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;
}
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 */
}
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 */ }
}
}
}
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.
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;
}
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
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.
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".
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.
Which of the following can be used as a replacement for /* missing statement */ so that the
sumEvens method works as intended?
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
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
}
Which of the following best describes the value returned by the method call calc(num) ?
The following declaration and method call appear in a method in the same class as insertionSort.
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.
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.
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
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.
Which of the following represents the arrays merged the first time the merge method is executed
as a result of the code segment above?
public static int binarySearch(int[] arr, int low, int high, int target)
{
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.
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
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.
What is the value of arrIndex after the code segment has been executed?
A. 4
B. 5
C. 6
D. 7
E. 10
7
The following code segment appears in a method in the same class as binarySearch.
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
/** 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)
{
}
The following code segment appears in a method in the same class as bSearch.
How many times will "right" be printed when the code segment is executed?
A. 1
B. 2
C. 3
D. 7
E. 8
9
/** 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)
{
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?
(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;
The following declaration and method call appear in a method in the same class as insertionSort.
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)
{
The following declaration and method call appear in the same class as selectionsort.
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.
Which of the following statements most accurately describes the time needed for operations on these data
structures?
Which of the following changes should be made so that selectSort will work as intended?
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?