Name:    APCS Java Unit 4 Practice Test - Arrays and Strings

Multiple Choice
Identify the choice that best completes the statement or answers the question.

1.

Consider the following method:

public static int[] what(int[] A)
{
int n = A.length;
int[] temp = new int[n] ;
for(int i=0; i<n; i++)
{
temp[i] = A[n-i-1];
}
return temp;
}

What is the the purpose of this method?
 a. To make an array that is a copy of the array A b. To make an array that is a copy of the array A in reverse order c. To make an array that is a scrambled copy of the array A d. To make an array that is filled with the negatives of the array A e. To make an array of random integers

2.

Suppose the method int sign(int x) returns 1 if x is positive, -1 if x is negative and 0 if x is 0. Given

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

what are the values of the elements of nums after the following code is executed?

for(int k=0; k<nums.length; k++)
{
nums[k] -= sign(nums[k]);
nums[k] += sign(nums[k]);
}
 a. -2, -1, 0, 1, 2 b. -1, 0, 0, 0, 1 c. 0, 0, 0, 0, 0 d. -2, 0, 0, 2, 3 e. -2, 0, 0, 0, 2

3.

Consider the following method:

// Returns true if there are duplicate values in
// the array parameter nums; false otherwise
public static boolean duplicates(int[] nums)
{
int j, k, n = nums.length;
<code>
}

Which of the following code segments can be used to replace <code> so that the method duplicates works as specified?
 I. for(j=0; j
 a. I only c. I and II only e. I, II and III b. II only d. I and III only

4.

What is the output of the following code segment?

String str1 = “Happy ”;
String str2 = str1;
str2 += “New Year! ”;
str1 = str2.substring(6);
System.out.println(str1 + str2)
 a. Happy New Year! b. Happy Happy New Year! c. New Year! New Year! d. New Year! Happy New Year! e. Happy New Year! Happy New Year!

5.

Consider the following method:

public static String process(String msg, String s)
{
int pos = msg.indexOf(s);
msg = msg.substring(0,pos) + " " + s;
return msg;
}

What is the output of the following code segment?

String s1 = "superstar";
String s2 = "star";
System.out.println(process(s1, s2));
 a. superstar b. superstarstar c. super star d. superstar star e. super starstar