Question 01

What value will be returned as a result of the call mystery(nums)?
(A) 5
(B) 6
(C) 7
(D) 10
(E) 17

The answer is option B the function will return the value 6 when the function mystery is called with nums passed as the argument as the values 2, then 1, then 1 then 2 will be added to x resulting in it being 6.

public static int mystery(int[] arr){
    int x = 0;
    
    for (int k = 0; k < arr.length; k = k + 2){
        x = x + arr[k];
    }

    return x;

}

int[] nums = {2, 6, 1, 0, 1, 4, 2};

mystery(nums);
6

Question 02

Which of the following code segments will compile without error?
(A) int x = obj.getA();
(B) int x; obj.getA(x);
(C) int x = obj.myA;
(D) int x = SomeClass.getA();
(E) int x = getA(obj);

The correct answer is option A the only program that will compile without error is option A it is the only way to access the getA() method for the object obj which as an instance of SomeClass.

public class SomeClass{
    private int myA;
    private int myB;
    private int myC;
    
    // Collegeboard did not implement constructor 
    // Needed addition to allow for code to run
    public SomeClass(int a, int b, int c) {
        this.myA = a;
        this.myB = b;
        this.myC = c;
    }
    
    public int getA(){ 
        return myA; 
    }
    public void setB(int value){ 
        myB = value; 
    }
}  

SomeClass obj = new SomeClass(1, 2, 3);

// Option A

int x = obj.getA();
// Option B

int x; obj.getA(x);
|    obj.getA(x);

method getA in class SomeClass cannot be applied to given types;

  required: no arguments

  found:    int

  reason: actual and formal argument lists differ in length
// Option C

int x = obj.myA;
|   int x = obj.myA;

myA has private access in SomeClass
// Option D

int x = SomeClass.getA();
|   int x = SomeClass.getA();

non-static method getA() cannot be referenced from a static context
// Option E

int x = getA(obj);
|   int x = getA(obj);

cannot find symbol

  symbol:   method getA(SomeClass)

Question 03

Which of the following changes to SomeClass will allow other classes to access but not modify the value of myC?
(A) Make myC public.

(B) Include the method:
public int getC()
{ return myC; }

(C) Include the method:
private int getC()
{ return myC; }

(D) Include the method:
public void getC(int x)
{ x = myC; }

(E) Include the method:
private void getC(int x)
{ x = myC; }

Option B is the correct answer as it implements a getter method to return the value for C without allowing the value to be modified while, option A will allow the value to be modified, option C will not allow the getter method to be accessed, while D will change the value for x and not return the value for myC, and option E will not allow the getter method to be accessed while also changing the value for x.

public class SomeClass{
    private int myA;
    private int myB;
    private int myC;
    
    // Collegeboard did not implement constructor 
    // Needed addition to allow for code to run
    public SomeClass(int a, int b, int c) {
        this.myA = a;
        this.myB = b;
        this.myC = c;
    }
    
    public int getA(){ 
        return myA; 
    }
    public void setB(int value){ 
        myB = value; 
    }

    public int getC(){
        return myC;
    }
} 




SomeClass obj = new SomeClass(1, 2, 3);

obj.getC();

3

Question 04

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

(A) Value is: 21
(B) Value is: 2.3333333
(C) Value is: 2
(D) Value is: 0
(E) Value is: 1

Option C is the correct answer as x = 7 which is less than 10 and y = 3 which is greater than 0 so integer division occurs between 7 and 3 resulting in 2.

int x = 7;
int y = 3;
if ((x < 10) && (y < 0))
 System.out.println("Value is: " + x * y);
else
 System.out.println("Value is: " + x / y); 
Value is: 2

Question 05

Which of the following is printed as a result of executing the following statement?

(A) [3, 4, 7, 12, 19, 28]
(B) [3, 4, 7, 12, 19, 28, 39]
(C) [4, 7, 12, 19, 28, 39]
(D) [39, 28, 19, 12, 7, 4]
(E) [39, 28, 19, 12, 7, 4, 3]

Option C is the correct answer with answer printing a 6 element list like the argument passed and the values being 11+3, 22+3, 33+3, 44+3, 55+3, 66+3 resulting in the output being [4, 7, 12, 19, 28, 39].

public ArrayList<Integer> mystery(int n) {
 ArrayList<Integer> seq = new ArrayList<Integer>();
 for (int k = 1; k <= n; k++)
 seq.add(new Integer(k * k + 3));
 return seq;
}

System.out.println(mystery(6)); 

[4, 7, 12, 19, 28, 39]

Question 06

Consider the following method that is intended to determine if the double values d1 and d2 are close enough to be considered equal. For example, given a tolerance of 0.001, the values 54.32271 and 54.32294 would be considered equal.

(A) return (d1 - d2) <= tolerance;
(B) return ((d1 + d2) / 2) <= tolerance;
(C) return (d1 - d2) >= tolerance;
(D) return ((d1 + d2) / 2) >= tolerance;
(E) return Math.abs(d1 - d2) <= tolerance;

Option E is the correct answer as it will return true if the absolute value of the difference between the two values is less than or equal to the tolerance. The other answers will not accurately determine that the two values are close enough to be considered equal as D finds if the average is greater than the tolerance. C will return true if the difference is greater than or equal to the tolerance not less than. B will return true if the average of the two values is less than or equal to the tolerance not the actual factor being determined, and A will return true if the difference is less than or equal to the tolerance but doesn’t factor that subtraction can result in negative option not matching the result.

double tolerance = 0.001;
double d1 = 54.32271;
double d2 = 54.32294;

public boolean almostEqual(double d1, double d2, double tolerance){
    return Math.abs(d1 - d2) <= tolerance; 
} 

System.out.println(almostEqual(d1, d2, tolerance));
System.out.println(Math.abs(d1-d2));
true


2.3000000000195087E-4

Question 07

Which of the following statements is the most appropriate for changing the name of student from “Thomas” to “Tom” ?

(A) student = new Person(“Tom”, 1995);
(B) student.myName = “Tom”;
(C) student.getName(“Tom”);
(D) student.setName(“Tom”);
(E) Person.setName(“Tom”);

Option D is the best option as it uses the setter method on the instance of the object Person and changes the name of the student in that form, instead of creating a new Person object with the name Tom, or getting the name of the student, or attempting to set the name on the class itself.

public class Person {
    private String myName;
    private int myYearOfBirth;

    public Person(String name, int yearOfBirth) {
        myName = name;
        myYearOfBirth = yearOfBirth;
    }

    public String getName() {
        return myName;
    }

    public void setName(String name) {
        myName = name;
    }
}

Person student = new Person("Thomas", 1995);

System.out.println(student.getName());

student.setName("Tom");

System.out.println(student.getName());
Thomas
Tom

Question 08

Which of the following declarations will compile without error?
I. Student a = new Student();
II. Student b = new Student(“Juan”, 15);
III. Student c = new Student(“Juan”, “15”);

(A) I only
(B) II only
(C) I and II only
(D) I and III only
(E) I, II, and III

Option C is the correct answer as both option I and II will compile without an error while option III tries to pass in a string as an argument for an integer value.

public class Student{
 private String myName;
 private int myAge;

 public Student(){ 
    // Addign implementation not given by Collegeboard 
    myName = "";
    myAge = 0;
 }
 
 public Student(String name, int age){ 
    // Adding implementation not given by Collegeboard 
    myName = name;
    myAge = age;
 }
 
}
// Option I

Student a = new Student();
// Option II

Student b = new Student("Juan", 15); 
// Option III

Student c = new Student("Juan", "15");
|   Student c = new Student("Juan", "15");

incompatible types: java.lang.String cannot be converted to int

Question 09

Consider the following method that is intended to return the sum of the elements in the array key.

public static int sumArray(int[] key){
 int sum = 0;
 for (int i = 1; i <= key.length; i++){
 /* missing code */
 }
 return sum;
}

Which of the following statements should be used to replace /* missing code */ so that sumArray will work as intended?

(A) sum = key[i];
(B) sum += key[i - 1];
(C) sum += key[i];
(D) sum += sum + key[i - 1];
(E) sum += sum + key[i];

Option B is the only option that will not receive an index out of bounds error as it counteracts the loop beginning at i = 1 when the array is 0 indexed. While not adding sum to itself like D.

// Option A

public static int sumArray(int[] key){
    int sum = 0;
    for (int i = 1; i <= key.length; i++){
        sum = key[i];
    }
    return sum;
}

int[] nums = {1, 2, 3, 4, 5};

System.out.println(sumArray(nums));
---------------------------------------------------------------------------

java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5

	at .sumArray(#12:6)

	at .(#14:1)
// Option B

public static int sumArray(int[] key){
    int sum = 0;
    for (int i = 1; i <= key.length; i++){
        sum += key[i - 1];
    }
    return sum;
}

int[] nums = {1, 2, 3, 4, 5};

System.out.println(sumArray(nums));
15
// Option C

public static int sumArray(int[] key){
    int sum = 0;
    for (int i = 1; i <= key.length; i++){
        sum += key[i];
    }
    return sum;
}

int[] nums = {1, 2, 3, 4, 5};

System.out.println(sumArray(nums));
---------------------------------------------------------------------------

java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5

	at .sumArray(#12:6)

	at .(#16:1)
// Option D

public static int sumArray(int[] key){
    int sum = 0;
    for (int i = 1; i <= key.length; i++){
        sum += sum + key[i];
    }
    return sum;
}

int[] nums = {1, 2, 3, 4, 5};

System.out.println(sumArray(nums));
---------------------------------------------------------------------------

java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5

	at .sumArray(#12:6)

	at .(#17:1)

Question 10

Consider the following instance variable and methods. You may assume that data has been initialized with length > 0. The methods are intended to return the index of an array element equal to target, or -1 if no such element exists.

private int[] data;

public int seqSearchRec(int target){
 return seqSearchRecHelper(target, data.length - 1);
}

private int seqSearchRecHelper(int target, int last){
    // Line 1
    if (data[last] == target)
        return last;
    else
        return seqSearchRecHelper(target, last - 1);
}
  1. For which of the following test cases will the call seqSearchRec(5) always result in an error?
    I. data contains only one element.
    II. data does not contain the value 5.
    III. data contains the value 5 multiple times.

(A) I only
(B) II only
(C) III only
(D) I and II only
(E) I, II, and III

Option B is the only correct answer as the function will always result in an out of bounds error if the 5 is not in the array. Option I will error only if the element in the array is not 5 and option III will not error. If the element is not found the program will keep searching until it reaches the end of the array and then reaches the negative first index resulting in an out of bounds error.

// Option I

private int[] data = {5};

public int seqSearchRec(int target){
    return seqSearchRecHelper(target, data.length - 1);
}

private int seqSearchRecHelper(int target, int last){
    // Line 1
    if (data[last] == target)
        return last;
    else
        return seqSearchRecHelper(target, last - 1);
} 

seqSearchRec(5);

// Only results in an error if single element in the array is not 5
0
// Option II

private int[] data = {1,2,3,4};

public int seqSearchRec(int target){
    return seqSearchRecHelper(target, data.length - 1);
}

private int seqSearchRecHelper(int target, int last){
    // Line 1
    if (data[last] == target)
        return last;
    else
        return seqSearchRecHelper(target, last - 1);
} 

seqSearchRec(5);

// Always results in an error
---------------------------------------------------------------------------

java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 4

	at .seqSearchRecHelper(#14:1)

	at .seqSearchRecHelper(#14:1)

	at .seqSearchRecHelper(#14:1)

	at .seqSearchRecHelper(#14:1)

	at .seqSearchRecHelper(#14:1)

	at .seqSearchRec(#13:1)

	at .(#19:3)
// Option III

private int[] data = {4,3,6,5,5,5};

public int seqSearchRec(int target){
    return seqSearchRecHelper(target, data.length - 1);
}

private int seqSearchRecHelper(int target, int last){
    // Line 1
    if (data[last] == target)
        return last;
    else
        return seqSearchRecHelper(target, last - 1);
} 

seqSearchRec(5);
5

Question 11

Which of the following should be used to replace // Line 1 in seqSearchRecHelper so that seqSearchRec will work as intended?

(A) if (last <= 0)
return -1;

(B) if (last < 0)
return -1;

(C) if (last < data.length)
return -1;

(D) while (last < data.length)

(E) while (last >= 0)

Option B is the correct answer as the code stops when the last index is less than 0 to prevent an out of bounds error. Option A will not find the value if it is the first element. Option C will never find the value as the last index will always be less than the length of the array. Option D and E will not work as there is no return statement.

// Option A

private int[] data = {5,1,2,3,4};

public int seqSearchRec(int target){
    return seqSearchRecHelper(target, data.length - 1);
}

private int seqSearchRecHelper(int target, int last){
    // Line 1
    if (last <= 0)
        return -1;

    if (data[last] == target)
        return last;
    else
        return seqSearchRecHelper(target, last - 1);
} 

seqSearchRec(5);

// If the first element is the one being searched 
// for the method will not function correctly
-1
// Option B

private int[] data = {5,1,2,3,4};

public int seqSearchRec(int target){
    return seqSearchRecHelper(target, data.length - 1);
}

private int seqSearchRecHelper(int target, int last){
    // Line 1
    if (last < 0)
        return -1;

    if (data[last] == target)
        return last;
    else
        return seqSearchRecHelper(target, last - 1);
} 

seqSearchRec(5);

// Method functions correctly
0
// Option C

private int[] data = {5,1,2,3,4};

public int seqSearchRec(int target){
    return seqSearchRecHelper(target, data.length - 1);
}

private int seqSearchRecHelper(int target, int last){
    // Line 1
    if (last < data.length)
        return -1;

    if (data[last] == target)
        return last;
    else
        return seqSearchRecHelper(target, last - 1);
} 

seqSearchRec(5);

// Method does not return actual index of target
-1
// Option D

private int[] data = {5,1,2,3,4};

public int seqSearchRec(int target){
    return seqSearchRecHelper(target, data.length - 1);
}

private int seqSearchRecHelper(int target, int last){
    // Line 1
    while (last < data.length)

    if (data[last] == target)
        return last;
    else
        return seqSearchRecHelper(target, last - 1);
} 

seqSearchRec(5);

// Method does not return actual index of target will always return -1 
// until loop terminates
|   private int seqSearchRecHelper(int target, int last){

|       // Line 1

|       while (last < data.length)

|   

|       if (data[last] == target)

|           return last;

|       else

|           return seqSearchRecHelper(target, last - 1);

|   }

missing return statement
// Option E

private int[] data = {5,1,2,3,4};

public int seqSearchRec(int target){
    return seqSearchRecHelper(target, data.length - 1);
}

private int seqSearchRecHelper(int target, int last){
    // Line 1
    while (last >= 0)
        
    if (data[last] == target)
        return last;
    else
        return seqSearchRecHelper(target, last - 1);
} 

seqSearchRec(5);

// Method functions correctly
|   private int seqSearchRecHelper(int target, int last){

|       // Line 1

|       while (last >= 0)

|           

|       if (data[last] == target)

|           return last;

|       else

|           return seqSearchRecHelper(target, last - 1);

|   }

missing return statement

Question 12

What is returned as a result of the call mystery(“computer”)?

(A) “computer”
(B) “cmue”
(C) “optr”
(D) “ompute”
(E) Nothing is returned because an IndexOutOfBoundsException is thrown.

Option C is the correct answer as the loop iterates the string and adds the element that is 2 elements after starting at the first element. So the output is o + p + t + r returning “optr”.

public String mystery(String input){
    String output = "";
    for (int k = 1; k < input.length(); k = k + 2){
        output += input.substring(k, k + 1);
    }

return output;
}

System.out.println(mystery("computer"));
optr

Question 13

int[] arr = {7, 2, 5, 3, 0, 10};
for (int k = 0; k < arr.length - 1; k++)
{
 if (arr[k] > arr[k + 1])
 System.out.print(k + " " + arr[k] + " ");
}

What will be printed as a result of executing the code segment?

(A) 0 2 2 3 3 0
(B) 0 7 2 5 3 3
(C) 0 7 2 5 5 10
(D) 1 7 3 5 4 3
(E) 7 2 5 3 3 0

Option B will be printed when the code segment is executed as iterate through the loop and print the value if it is greater than the element that follows it and the iteration thus 0, followed by 7 as it is greater than 2, then 2 as nothing is printed on the prior run, then 5 as it is greater than 3, then 3 the run number, then 3 as it is greater than 3.

int[] arr = {7, 2, 5, 3, 0, 10};

for (int k = 0; k < arr.length - 1; k++){
    if (arr[k] > arr[k + 1])
        System.out.print(k + " " + arr[k] + " ");
}

0 7 2 5 3 3 

Question 14

Which of the following can be used to replace /* expression */ so that getTotalMileage returns the total of the miles traveled for all vehicles in the fleet?

(A) getMileage(v)
(B) myVehicles[v].getMileage()
(C) Vehicle.get(v).getMileage()
(D) myVehicles.get(v).getMileage()
(E) v.getMileage()

Option E would be the only option that would work as through iterating through the array list of vehicles the getMileage() method would need to be called on each object to get their respective mileage and add it to the total.

import java.util.ArrayList;

public interface Vehicle {
    /* @return the mileage traveled by this Vehicle */
    double getMileage();
}

public class Fleet {
    private ArrayList<Vehicle> myVehicles;

    public Fleet() {
        myVehicles = new ArrayList<>();
    }

    public Fleet(ArrayList<Vehicle> vehicles) {
        myVehicles = new ArrayList<>(vehicles);
    }

    public void addVehicle(Vehicle vehicle) {
        myVehicles.add(vehicle);
    }

    /** @return the mileage traveled by all vehicles in this Fleet */
    public double getTotalMileage() {
        double sum = 0.0;
        for (Vehicle v : myVehicles) {
            sum += v.getMileage(); //Option E, get mileage from vehicle instance and then sums it only logical option
        }
        return sum;
    }
}

Question 15

Consider the following method, isSorted, which is intended to return true if an array of integers is sorted in nondecreasing order and to return false otherwise.

/* @param data an array of integers 
@return true if the values in the array appear in sorted (nondecreasing) order */
public static boolean isSorted(int[] data){
    /* missing code */
} 

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

(A) I only
(B) II only
(C) III only
(D) I and II only
(E) I and III only

Option A is the correct answer with only option I returning if the array is sorted through beginning at the first index and then determining if the element that precedes it is smaller than it, then continues till the k is less than the length of the array, option II will have a out of bounds error attempting to add 1 to the index to determine the next value, option III cannot determine if the array is actually sorted.

// Option I

public static boolean isSorted(int[] data){
    for (int k = 1; k < data.length; k++){
        if (data[k - 1] > data[k])
            return false;
    }
    
    return true;
} 


int[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] array2 = {7, 15, 2, 19, 4, 342, 1, 0, 9, 11};

System.out.println(isSorted(array1));
System.out.println(isSorted(array2));

// Correctly determines if the array is sorted
true
false
// Option II
public static boolean isSorted(int[] data){
    for (int k = 0; k < data.length; k++){
        if (data[k] > data[k + 1])
        return false;
    }
    
    return true;
} 

int[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] array2 = {7, 15, 2, 19, 4, 342, 1, 0, 9, 11};

System.out.println(isSorted(array1));
System.out.println(isSorted(array2));

// Does not properly determine if the array is sorted
---------------------------------------------------------------------------

java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10

	at .isSorted(#12:4)

	at .(#18:1)
// Option III

public static boolean isSorted(int[] data){
    for (int k = 0; k < data.length - 1; k++){
        if (data[k] > data[k + 1])
            return false;
        else
            return true;
    }
    
    return true;
} 


int[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] array2 = {7, 15, 2, 19, 4, 342, 1, 0, 9, 11};

System.out.println(isSorted(array1));
System.out.println(isSorted(array2));

// Does not correctly return if the array is sorted or not
true


true

Question 16

Consider the following incomplete method that is intended to return an array that contains the contents of its first array parameter followed by the contents of its second array parameter.

public static int[] append(int[] a1, int[] a2)
{
 int[] result = new int[a1.length + a2.length];
 for (int j = 0; j < a1.length; j++)
 result[j] = a1[j];
 for (int k = 0; k < a2.length; k++)
 result[ /* index */ ] = a2[k];
 return result;
} 

Which of the following expressions can be used to replace /* index */ so that append will work as intended?
(A) j
(B) k
(C) k + a1.length - 1
(D) k + a1.length
(E) k + a1.length + 1

Option D is the only option that will allow the code to work as intended as the change ensures that the code copies the elements of a2 directly following the final index of the element in the last array. This is why option C will be incorrect as well as the option subtracts by one not actually appending past the last element within the array. Options A and B are the variables that are used to iterate through the elements within the arrays and are not valid options.

// Option A

public static int[] append(int[] a1, int[] a2){
    int[] result = new int[a1.length + a2.length];
    for (int j = 0; j < a1.length; j++)
        result[j] = a1[j];
    for (int k = 0; k < a2.length; k++)
        result[j] = a2[k];
    return result;
}

int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
int[] newArr = append(arr1, arr2);
System.out.println(Arrays.toString(newArr));
|   // Option A

|   

|   public static int[] append(int[] a1, int[] a2){

|       int[] result = new int[a1.length + a2.length];

|       for (int j = 0; j < a1.length; j++)

|           result[j] = a1[j];

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

|           result[j] = a2[k];

|       return result;

|   }

Unresolved dependencies:

   - variable j
// Option B

public static int[] append(int[] a1, int[] a2){
    int[] result = new int[a1.length + a2.length];
    for (int j = 0; j < a1.length; j++)
        result[j] = a1[j];
    for (int k = 0; k < a2.length; k++)
        result[k] = a2[k];
    return result;
}


int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
int[] newArr = append(arr1, arr2);
System.out.println(Arrays.toString(newArr));
[4, 5, 6, 0, 0, 0]
// Option C

public static int[] append(int[] a1, int[] a2){
    int[] result = new int[a1.length + a2.length];
    for (int j = 0; j < a1.length; j++)
        result[j] = a1[j];
    for (int k = 0; k < a2.length; k++)
        result[k + a1.length - 1] = a2[k];
    return result;
}


int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
int[] newArr = append(arr1, arr2);
System.out.println(Arrays.toString(newArr));
[1, 2, 4, 5, 6, 0]
// Option D

public static int[] append(int[] a1, int[] a2){
    int[] result = new int[a1.length + a2.length];
    for (int j = 0; j < a1.length; j++)
        result[j] = a1[j];
    for (int k = 0; k < a2.length; k++)
        result[k + a1.length] = a2[k];    
    return result;
}


int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
int[] newArr = append(arr1, arr2);
System.out.println(Arrays.toString(newArr));

[1, 2, 3, 4, 5, 6]
// Option E

public static int[] append(int[] a1, int[] a2){
    int[] result = new int[a1.length + a2.length];
    for (int j = 0; j < a1.length; j++)
        result[j] = a1[j];
    for (int k = 0; k < a2.length; k++)
        result[k + a1.length + 1] = a2[k];
    return result;
}


int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
int[] newArr = append(arr1, arr2);
System.out.println(Arrays.toString(newArr));
---------------------------------------------------------------------------

java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6

	at .append(#12:8)

	at .(#22:1)

Question 17

Consider the following code segment.

int[] arr = {1, 2, 3, 4, 5, 6, 7};

for (int k = 3; k < arr.length - 1; k++)
    arr[k] = arr[k + 1];

Which of the following represents the contents of arr as a result of executing the code segment?

(A) {1, 2, 3, 4, 5, 6, 7}
(B) {1, 2, 3, 5, 6, 7}
(C) {1, 2, 3, 5, 6, 7, 7}
(D) {1, 2, 3, 5, 6, 7, 8}
(E) {2, 3, 4, 5, 6, 7, 7}

Option C is the correct answer as the code beings with the third index or the fourth element in array and all preceding elements are shifted forwards one resulting in the new array being {1, 2, 3, 5, 6, 7, 7} seven is repeated as the last element is copied to another new index.

int[] arr = {1, 2, 3, 4, 5, 6, 7};

for (int k = 3; k < arr.length - 1; k++)
    arr[k] = arr[k + 1];

System.out.println(Arrays.toString(arr));
[1, 2, 3, 5, 6, 7, 7]

Question 18

Assume that myList is an ArrayList that has been correctly constructed and populated with objects. Which of the following expressions produces a valid random index for myList ?

(A) (int)( Math.random() * myList.size() ) - 1
(B) (int)( Math.random() * myList.size() )
(C) (int)( Math.random() * myList.size() ) + 1
(D) (int)( Math.random() * (myList.size() + 1) )
(E) Math.random(myList.size())

Option B will return a correct value as it always returns a index within the bounds of the input array through multiplying a random value against the length of the array then casting it to an integer resulting in it being less than than the maximum index, option A allows for the index -1, and C, and D allow for a value 1 greater than the maximum index.

// Defining myList
ArrayList<Integer> myList = new ArrayList<Integer>();

Random rand = new Random();
for (int i = 0; i < 10; i++) {
    myList.add(rand.nextInt(100) + 1);
}

System.out.println(myList);
[61, 51, 30, 81, 52, 91, 66, 20, 78, 91]
// Option A
System.out.println(myList);
System.out.println((int)( Math.random() * myList.size() ) - 1)
[85, 32, 79, 36, 46, 97, 48, 39, 57, 29]
-1
// Option B
System.out.println(myList);
System.out.println((int)( Math.random() * myList.size() ))
[85, 32, 79, 36, 46, 97, 48, 39, 57, 29]
1
// Option C
System.out.println(myList);
System.out.println((int)( Math.random() * myList.size() ) + 1)
[85, 32, 79, 36, 46, 97, 48, 39, 57, 29]
2
// Option D
System.out.println(myList);
System.out.println((int)( Math.random() * (myList.size() + 1) ))
[85, 32, 79, 36, 46, 97, 48, 39, 57, 29]
2
// Option E
System.out.println(myList);
Math.random(myList.size())
[85, 32, 79, 36, 46, 97, 48, 39, 57, 29]



|   Math.random(myList.size())

method random in class java.lang.Math cannot be applied to given types;

  required: no arguments

  found:    int

  reason: actual and formal argument lists differ in length

Question 19

Assume that a and b have been defined and initialized as int values. The expression

!(!(a != b ) && (b > 7)) 
// !(a != b ) = !(a = b) = (a != b)
// !((a != b ) && (b > 7)) = (a != b ) || (b > 7)  

is equivalent to which of the following?

(A) (a != b) || (b < 7)
(B) (a != b) || (b <= 7)
(C) (a == b) || (b <= 7)
(D) (a != b) && (b <= 7)
(E) (a == b) && (b > 7)

Option B is the correct answer as A, and D while correct containing (a != b) do not correctly have the second element as less than 7 is not equal to greater than 7. And option D does not include the negation of the and making it an or. Thus Option b has to be the only correct answer.

Question 20

Consider the following method.

Which of the following describes what the method arrayMethod() does to the array nums?
(A) The array nums is unchanged.
(B) The first value in nums is copied to every location in the array.
(C) The last value in nums is copied to every location in the array.
(D) The method generates an ArrayIndexOutOfBoundsException.
(E) The contents of the array nums are reversed.

Option E is the correct answer there is a while loop that sets the iterates through the indexes from the first and last index and swaps the values until the indexes meet in the middle resulting in the array being reversed.

public static void arrayMethod(int nums[]){
    int j = 0;
    int k = nums.length - 1;
    while (j < k){
        int x = nums[j];
        nums[j] = nums[k];
        nums[k] = x;
        j++;
        k--;
    }
}

int[] arr = {1, 2, 3, 4, 5, 6, 7};

arrayMethod(arr);

System.out.println(Arrays.toString(arr));
[7, 6, 5, 4, 3, 2, 1]

Question 21

Consider the following method, which is intended to return the element of a 2-dimensional array that is closest in value to a specified number, val.

/* @return the element of 2-dimensional array mat whose value is closest to val */
public double findClosest(double[][] mat, double val) {
    double answer = mat[0][0];
    double minDiff = Math.abs(answer - val);
    for (double[] row : mat){
        for (double num : row){
            if ( /* missing code */ ){
                answer = num;
                minDiff = Math.abs(num - val);
            }
        }
    }
    return answer;
}

Which of the following could be used to replace /* missing code */ so that findClosest will work as intended?
(A) val - row[num] < minDiff
(B) Math.abs(num - minDiff) < minDiff
(C) val - num < 0.0
(D) Math.abs(num - val) < minDiff
(E) Math.abs(row[num] - val) < minDiff

Option D is the only option that will correctly return the closest value to the target value. This is done as the code determines if the first value at in the first value in the first array is smaller than the difference between the first value and the target value originally thus to find another value closer to the target the difference must be smaller which option B achieves then allows it to be assigns to the value for minDiff while factoring in that subtraction can have a negative value through the use of the absolute value.

// Option A

public double findClosest(double[][] mat, double val) {
    double answer = mat[0][0];
    double minDiff = Math.abs(answer - val);
    for (double[] row : mat){
        for (double num : row){
            if (val - row[num] < minDiff){
                answer = num;
                minDiff = Math.abs(num - val);
            }
        }
    }
    return answer;
}

double[][] arr = {  {1, 2, 3}, {4, 5, 6}  };
System.out.println(findClosest(arr, 5.2));

|               if (val - row[num] < minDiff){

incompatible types: possible lossy conversion from double to int
// Option B
public double findClosest(double[][] mat, double val) {
    double answer = mat[0][0];
    double minDiff = Math.abs(answer - val);
    for (double[] row : mat){
        for (double num : row){
            if (Math.abs(num - val) < minDiff){
                answer = num;
                minDiff = Math.abs(num - val);
            }
        }
    }
    return answer;
}

double[][] arr = {  {1, 2, 3}, {4, 5, 6}  };
System.out.println(findClosest(arr, 5.2));

5.0
// Option C

public double findClosest(double[][] mat, double val) {
    double answer = mat[0][0];
    double minDiff = Math.abs(answer - val);
    for (double[] row : mat){
        for (double num : row){
            if (val - num < 0.0){
                answer = num;
                minDiff = Math.abs(num - val);
            }
        }
    }
    return answer;
}

double[][] arr = {  {1, 2, 3}, {4, 5, 6}  };
System.out.println(findClosest(arr, 5.2));
6.0
// Option D

public double findClosest(double[][] mat, double val) {
    double answer = mat[0][0];
    double minDiff = Math.abs(answer - val);
    for (double[] row : mat){
        for (double num : row){
            if (Math.abs(num - val) < minDiff){
                answer = num;
                minDiff = Math.abs(num - val);
            }
        }
    }
    return answer;
}

double[][] arr = {  {1, 2, 3}, {4, 5, 6}  };
System.out.println(findClosest(arr, 5.2));
5.0
// Option E

public double findClosest(double[][] mat, double val) {
    double answer = mat[0][0];
    double minDiff = Math.abs(answer - val);
    for (double[] row : mat){
        for (double num : row){
            if (Math.abs(row[num] - val) < minDiff){
                answer = num;
                minDiff = Math.abs(num - val);
            }
        }
    }
    return answer;
}

double[][] arr = {  {1, 2, 3}, {4, 5, 6}  };
System.out.println(findClosest(arr, 5.2));

|               if (Math.abs(row[num] - val) < minDiff){

incompatible types: possible lossy conversion from double to int

Question 22

Consider the following Book and AudioBook classes.

Which of the following best explains why the code segment will not compile?

(A) Line 2 will not compile because variables of type Book may not refer to variables of type AudioBook.
(B) Line 4 will not compile because variables of type Book may only call methods in the Book class.
(C) Line 5 will not compile because the AudioBook class does not have a method named toString declared or implemented.
(D) Line 6 will not compile because the statement is ambiguous. The compiler cannot determine which length method should be called.
(E) Line 7 will not compile because the element at index 1 in the array named books may not have been initialized.

Option B as the parent class cannot call the methods of the child class as the parent class does not have access to the methods of the child class the other functions have no issues.

public class Book{
    private int numPages;
    private String bookTitle;
    public Book(int pages, String title){
        numPages = pages;
        bookTitle = title;
    }
    public String toString(){
        return bookTitle + " " + numPages;
    }
    public int length(){
        return numPages;
    }
}

public class AudioBook extends Book{
    private int numMinutes;
    public AudioBook(int minutes, int pages, String title){
        super(pages, title);
        numMinutes = minutes;
    }
    public int length(){
        return numMinutes;
    }
 
    public double pagesPerMinute(){
        return ((double) super.length()) / numMinutes;
    }
} 

Book[] books = new Book[2]; //Line 1

books[0] = new AudioBook(100, 300, "The Jungle"); // Line 2

The Jungle 300
books[1] = new Book(400, "Captains Courageous"); // Line 3 

Captains Courageous 400
System.out.println(books[0].pagesPerMinute()); // Line 4

|   System.out.println(books[0].pagesPerMinute()); // Line 4

cannot find symbol

  symbol:   method pagesPerMinute()
System.out.println(books[0].toString()); // Line 5

The Jungle 300
System.out.println(books[0].length()); // Line 6

100
System.out.println(books[1].toString()); // Line 7

Captains Courageous 400

Question 23

Consider the following instance variable and method manipulate.

What will the contents of animals be as a result of calling manipulate?
(A) [“baboon”, “zebra”, “bass”, “cat”, “bear”, “koala”]
(B) [“bear”, “zebra”, “bass”, “cat”, “koala”, “baboon”]
(C) [“baboon”, “bear”, “zebra”, “bass”, “cat”, “koala”]
(D) [“bear”, “baboon”, “zebra”, “bass”, “cat”, “koala”]
(E) [“zebra”, “cat”, “koala”, “baboon”, “bass”, “bear”]

Option B is the correct answer with the code segment attempting to move the element to front of the array however the current position is subtracted from the length of the array resulting in the position not changing.

List<String> animals = new ArrayList<>(Arrays.asList("bear", "zebra", "bass", "cat", "koala", "baboon"));

private void manipulate(List<String> animals){
    for (int k = animals.size() - 1; k > 0; k--){
        if (animals.get(k).substring(0, 1).equals("b")){
            animals.add(animals.size() - k, animals.remove(k));
        }
    }
}

manipulate(animals);

System.out.println(animals);


[bear, zebra, bass, cat, koala, baboon]

Question 24

What is printed as a result of executing the code segment? (A) 3
(B) 4
(C) 5
(D) 7
(E) 8

Option D is the correct answer as the code segment iterates through the rows assigning the current element to each column until the amount of rows is divisible by three aka the end of the column then moving on to the next column and setting rows to 0 until a 3 by 3 array is made. This means on the first row and in the third column 7 will be assigned.

int[] oldArray = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[][] newArray = new int[3][3];
int row = 0;
int col = 0;

for (int value : oldArray){
    newArray[row][col] = value;
    row++;
    if ((row % 3) == 0){
        col++;
        row = 0;
    }
}

System.out.println(newArray[0][2]); 

7

Question 25

A rectangular box fits inside another rectangular box if and only if the height, width, and depth of the smaller box are each less than the corresponding values of the larger box. Consider the following three interface declarations that are intended to represent information necessary for rectangular boxes.

I. public interface RBox

{
 /** @return the height of this RBox */
 double getHeight();
 /** @return the width of this RBox */
 double getWidth();
 /** @return the depth of this RBox */
 double getDepth();
}

II. public interface RBox

{
 /** @return true if the height of this RBox is less than the height of other;
 * false otherwise
 */
 boolean smallerHeight(RBox other);
 /** @return true if the width of this RBox is less than the width of other;
 * false otherwise
 */
 boolean smallerWidth(RBox other);
 /** @return true if the depth of this RBox is less than the depth of other;
 * false otherwise
 */
 boolean smallerDepth(RBox other);
}

III. public interface RBox

    {
    /** @return the surface area of this RBox */
    double getSurfaceArea();
    /** @return the volume of this RBox */
    double getVolume();
    }

Which of the interfaces, if correctly implemented by a Box class, would be sufficient functionality for a user of the Box class to determine if one Box can fit inside another?
(A) I only
(B) II only
(C) III only
(D) I and II only
(E) I, II, and III

Option D as I and III allow for the user to see if the dimensions would allow for the boxes to fit in each other however in III the volume would be insufficient at the boxes can have different dimensions but the same volume and thus not fit.

Question 26

Assume that the array arr has been defined and initialized as follows.

int[] arr = /* initial values for the array */ ;

Which of the following will correctly print all of the odd integers contained in arr but none of the even integers contained in arr?

(A) for (int x : arr)
if (x % 2 == 1)
System.out.println(x);

(B) for (int k = 1; k < arr.length; k++)
if (arr[k] % 2 == 1)
System.out.println(arr[k]);

(C) for (int x : arr)
if (x % 2 == 1)
System.out.println(arr[x]);

(D) for (int k = 0; k < arr.length; k++)
if (arr[k] % 2 == 1)
System.out.println(k);

(E) for (int x : arr)
if (arr[x] % 2 == 1)
System.out.println(arr[x]);

Option A as it is the only one that checks if every value within the array is not divisible by 2 thus being odd. Option B is similar however due to initializing the loop with k=1 and using indices it will skip the first element.

int[] arr = {1,2,3,4,5,6,7,8,9,10}
// Option A

for (int x : arr)
    if (x % 2 == 1)
        System.out.println(x);
1
3
5
7
9
// Option B

for (int k = 1; k < arr.length; k++)
    if (arr[k] % 2 == 1)
        System.out.println(arr[k]);
3
5
7
9
// Option C

for (int x : arr)
    if (x % 2 == 1)
        System.out.println(arr[x]);
2
4
6
8
10
// Option D

for (int k = 0; k < arr.length; k++)
    if (arr[k] % 2 == 1)
        System.out.println(k);
0
2
4
6
8
// Option E

for (int x : arr)
    if (arr[x] % 2 == 1)
        System.out.println(arr[x]);
3
5
7
9



---------------------------------------------------------------------------

java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10

	at .(#31:4)

Question 27

What value is returned as a result of the call mystery(6)?
(A) 1
(B) 5
(C) 6
(D) 8
(E) 13

Option D is the answer with the method mystery being called in with 6 as the argument as 6 is greater than 2 thus will iterate through the loop 4 times adding 1 to x so x equals 2 then 1 so it equals 3, then 2 so it equals 5, then 3 getting 8.

Question 28

Which of the following is true of method mystery?
(A) x will sometimes be 1 at // Point B.
(B) x will never be 1 at // Point C.
(C) n will never be greater than 2 at // Point A.
(D) n will sometimes be greater than 2 at // Point C.
(E) n will always be greater than 2 at // Point B.

Option E is the correct answer as to enter the while loop and remain in the while loop n must be greater than 2 at point B. The option are simply untrue.

public static int mystery(int n){
    int x = 1;
    int y = 1;
    // Point A
    while (n > 2){
        x = x + y;
        // Point B
        y = x - y;
        n--;
    }

    // Point C
    return x;
} 

mystery(6)
8

Question 29

Consider the following code segment.

for (int k = 1; k <= 100; k++)
    if ((k % 4) == 0)
        System.out.println(k);

Which of the following code segments will produce the same output as the code segment above?

(A) for (int k = 1; k <= 25; k++)
System.out.println(k);

(B) for (int k = 1; k <= 100; k = k + 4)
System.out.println(k);

(C) for (int k = 1; k <= 100; k++)
System.out.println(k % 4);

(D) for (int k = 4; k <= 25; k = 4 * k)
System.out.println(k);

(E) for (int k = 4; k <= 100; k = k + 4)
System.out.println(k);

Option E as it is the only option that prints all values divisible by 4 between 1 and 100 as seen in the original code segment. Through adding 4 to itself until it is not less than or equal to 100.

// Base
for (int k = 1; k <= 100; k++)
    if ((k % 4) == 0)
        System.out.println(k);
// Option A

for (int k = 1; k <= 25; k++)
    System.out.println(k);
// Option B

for (int k = 1; k <= 100; k = k + 4)
    System.out.println(k);
// Option C

for (int k = 1; k <= 100; k++)
    System.out.println(k % 4);
// Option D

for (int k = 4; k <= 25; k = 4 * k)
    System.out.println(k);
// Option E

for (int k = 4; k <= 100; k = k + 4)
    System.out.println(k);

Question 30

Consider the following method.

public static String scramble(String word, int howFar){
    return word.substring(howFar + 1, word.length()) +
    word.substring(0, howFar);
} 

What value is returned as a result of the call scramble(“compiler”, 3)?
(A) “compiler”
(B) “pilercom”
(C) “ilercom”
(D) “ilercomp”
(E) No value is returned because an IndexOutOfBoundsException will be thrown.

Option C is the correct answer as the method will go to the index that is one greater than argument passed or the fourth index to this case to the end of the string and then add the first three indices to the string which will result in the end string ‘ilercom’.

public static String scramble(String word, int howFar){
    return word.substring(howFar + 1, word.length()) +
    word.substring(0, howFar);
}

scramble("compiler", 3)
ilercom

Question 31

public void mystery(int[] data){
    for (int k = 0; k < data.length - 1; k++)
        data[k + 1] = data[k] + data[k + 1];
} 

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

int[] values = {5, 2, 1, 3, 8};
mystery(values);

for (int v : values)
    System.out.print(v + " ");

System.out.println();

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

(A) 5 2 1 3 8
(B) 5 7 3 4 11
(C) 5 7 8 11 19
(D) 7 3 4 11 8
(E) Nothing is printed because an ArrayIndexOutOfBoundsException is thrown during the execution of method mystery.

Option C is the correct answer as the mystery method will add the sum of all prior elements to the current element then assign that value to the element thus the output will be 5, 7, 8, 11, 19 which will then be printed with a space between each element.

public void mystery(int[] data){
    for (int k = 0; k < data.length - 1; k++)
        data[k + 1] = data[k] + data[k + 1];
} 

int[] values = {5, 2, 1, 3, 8};
mystery(values);

for (int v : values)
    System.out.print(v + " ");

System.out.println();

5 7 8 11 19 

Question 32

Consider the following method.

public int compute(int n, int k){
    int answer = 1;
    for (int i = 1; i <= k; i++)
        answer *= n;
    return answer;
}

Which of the following represents the value returned as a result of the call compute(n, k)?

(A) n*k
(B) n!
(C) n^k
(D) 2^k
(E) k^n

Option C is the correct answer as the method will multiply n by itself k times resulting in n^k.

public int compute(int n, int k){
    int answer = 1;
    for (int i = 1; i <= k; i++)
        answer *= n;
    return answer;
}

compute(2, 3)
8

Question 33

Consider the following method.

int sum = 0;
int k = 1;

while (sum < 12 || k < 4)
    sum += k;

System.out.println(sum); 

What is printed as a result of executing the code segment?
(A) 6
(B) 10
(C) 12
(D) 15
(E) Nothing is printed due to an infinite loop.

Option E is the correct answer the loop will never terminate there is no break condition as k is not being incremented thus there is no way for the or condition to be true as k < 4 will always be true.

Question 34

public class Point{
    private double x; // x-coordinate
    private double y; // y-coordinate
    public Point(){
        x = 0;
        y = 0;
    }
    public Point(double a, double b){
        x = a;
        y = b;
    }
    // There may be instance variables, constructors, and methods that are not shown.
}

public class Circle{
    private Point center;
    private double radius;
    /* Constructs a circle where (a, b) is the center and r is the radius.*/
    public Circle(double a, double b, double r){
        /* missing code */
    }
} 

Which of the following replacements for /* missing code */ will correctly implement the Circle constructor?

I. center = new Point(); radius = r;

II. center = new Point(a, b); radius = r;

III. center = new Point(); center.x = a; center.y = b; radius = r;

(A) I only
(B) II only
(C) III only
(D) II and III only
(E) I, II, and III

Option B is the correct answer as it is the only option that correctly initializes the center point and the radius for the Circle class. The I does not correctly define the point, nor does III.

Question 35

Consider the following code segment.

int num = 2574;
int result = 0;

while (num > 0){
    result = result * 10 + num % 10;
    num /= 10;
}

System.out.println(result);

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

(A) 2
(B) 4
(C) 18
(D) 2574
(E) 4752

Option E will be correct answer as the code add the remainder of dividing by 10 which is 4 in the first iteration to which the result times 10, increasing 10 fold per loop as result begins at 4 it will be (0 x 10) + 4 for the first iteration, (4 x 10) + 7 = 47 for the second loop, (47 x 10) + 5 = 52 for the third loop, and so on and so forth till the value 4752 is reached.


int num = 2574;
int result = 0;

while (num > 0){
    result = result * 10 + num % 10;
    num /= 10;
}

System.out.println(result);
4752

Question 36

Consider the following method.

public void test(int x){
    int y;
    if (x % 2 == 0)
        y = 3;
    else if (x > 9)
        y = 5;
    else
        y = 1;
    System.out.println("y = " + y);
} 

Which of the following test data sets would test each possible output for the method?

(A) 8, 9, 12
(B) 7, 9, 11
(C) 8, 9, 11
(D) 8, 11, 13
(E) 7, 9, 10

Option C as the input 8 can test the condition for values that are divisible by 2, 9 for values that are not greater than 9 or evenly disable by 2, and 11 for values that are greater than 9 and not evenly divisible by 2.

public void test(int x){
    int y;
    if (x % 2 == 0)
        y = 3;
    else if (x > 9)
        y = 5;
    else
        y = 1;
    System.out.println("y = " + y);
}
// Option A
test(8); // tests for values disable evenly by 2
test(9); // Tests for the the third condition
test(12); // Does not test for second condition as it is also evenly devisable by 2
y = 3
y = 1
y = 3
// Option B

test(7); // Tests for third condition
test(9); // Tests for third condition
test(11); // Tests for second condition
y = 1
y = 1
y = 5
// Option C

test(8); // Tests for first condition
test(9); // Tests for third condition
test(11); // Tests for the second condition
y = 3
y = 1
y = 5
// Option D

test(8); // First
test(11); // Second
test(13); // Second
y = 3
y = 5
y = 5
// Option E

test(7); // Third
test(9); // Third
test(10); // First
y = 1
y = 1
y = 3

Question 37

Consider the following code segment.

int x = 1;
while ( /* missing code */ )
{
 System.out.print(x + " ");
 x = x + 2;
}

Consider the following possible replacements for /* missing code */.
I. x < 6
II. x != 6
III. x < 7

Which of the proposed replacements for /* missing code */ will cause the code segment to print only the values 1 3 5 ?

(A) I only
(B) II only
(C) I and II only
(D) I and III only
(E) I, II, and III

Option D as x is being incremented by 2 if the condition is either x < 6 the loop will terminate before the next value which is 7 is printed or if the value is x < 7 as the loop increments x by 2 will also stop it from being printed. x can never equal 6 and thus the loop will never terminate if the condition is x != 6.

// Option I
int x = 1;
while (x < 6)
{
 System.out.print(x + " ");
 x = x + 2;
}
1 3 5 
// Option II
int x = 1;
while (x < 7)
{
 System.out.print(x + " ");
 x = x + 2;
}
1 3 5 

Question 38

Assume that x and y have been declared and initialized with int values. Consider the following Java expression.

(y > 10000) || (x > 1000 && x < 1500)

Which of the following is equivalent to the expression given above?

(A) (y > 10000 || x > 1000) && (y > 10000 || x < 1500)
(B) (y > 10000 || x > 1000) || (y > 10000 || x < 1500)
(C) (y > 10000) && (x > 1000 || x < 1500)
(D) (y > 10000 && x > 1000) || (y > 10000 && x < 1500)
(E) (y > 10000 && x > 1000) && (y > 10000 && x < 1500)

Option A is the only correct answer as the or condition can be distributed into the and condition as if the y > 10000 condition was true it would execute regardless of the and being false which is preserved, along with the base condition of both x > 1000 and x < 1500 being true would also ensure the code segment executes.

Question 39

Consider the following recursive method.

public int recur(int n){
 if (n <= 10)
 return n * 2;
 else
 return recur(recur(n / 3));
}

What value is returned as a result of the call recur(27) ?

(A) 8
(B) 9
(C) 12
(D) 16
(E) 18

Option D 16 is returned recur calls it self with a value a third that of the original condition if it is less than or equal to 10 which it is so on the second call is on the output of the input 27/3 which is 9 is passed in so 9*2 is returned which is 18 which is then passed in again 18/3 which is 6 which is then returned as 12 which is then passed in so the process repeats 12/3 = 4 –> 8 –> 16 which is the final output.

public int recur(int n){
    if (n <= 10)
        return n * 2;
    else
        return recur(recur(n / 3));
}

int output = recur(27);
System.out.println(output);
16

Question 40

Consider the following recursive method.

public static void whatsItDo(String str){
    int len = str.length();
    if (len > 1){
        String temp = str.substring(0, len  1);
        whatsItDo(temp);
        System.out.println(temp);
    }
}

What is printed as a result of the call whatsItD(“WATCH”)?

(A)
WATC
WAT
WA
W

(B)
WATCH
WATC
WAT
WA

(C)
W
WA
WAT
WATC

(D)
W
WA
WAT
WATC
WATCH

(E)
WATCH
WATC
WAT
WA
W
WA
WAT
WATC
WATCH

Option C is printed a result of executing the code segment as teh function what whatItDo creates a new substring temp which is equivalent to WATC then class it self on WATC resulting in WAT, then, WA, then finally W. As the condition is called before the print statement the code will execute the print statements as W, WA, WAT, WATC because the recursive conditions are executed then prints resulting in the values printed being in reserve order of the recursive calls.

public static void whatsItDo(String str){
    int len = str.length();
    if (len > 1){
        String temp = str.substring(0, len - 1);
        whatsItDo(temp);
        System.out.println(temp);
    }
}

whatsItDo("WATCH")

W
WA
WAT
WATC