AP Computer Science A • Unit 2.10

Implementing String Algorithms

Detailed answer explanations for the Unit 2.10 multiple-choice practice questions.

Q1B
Q2C
Q3D
Q4C
Q5A
Q6A
Q7A
Q8B
Q9D
Q10A
Q11B
Q12D
Q13A
Q14B
Q15D
Q16B
Q17C
Q18A
How to use this page: First try each question without looking at the explanation. Then compare your answer with the key and read why the other choices are not correct.

Answer Explanations

Q1

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

String s = "planet";
String part = s.substring(2, 5);

System.out.println(part);
Apla
Bane
Canet
Dnet
Correct answer: B. substring(2, 5) starts at index 2 and stops before index 5, so it returns ane.
Explanation

A two-argument substring call includes the character at the start index and excludes the character at the end index. In "planet" the characters at indices 2, 3, and 4 are a, n, and e.

  • A is not correct: pla is the first three characters, which is what a start index of 0 would produce.
  • C is not correct: anet includes the character at index 5, but the end index is excluded.
  • D is not correct: net begins at index 3, one position past the start index given in the call.
Q2

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

String s = "mississippi";
int count = 0;

for (int i = 0; i < s.length(); i++) {
    String ch = s.substring(i, i + 1);

    if (ch.equals("s")) {
        count++;
    }
}

System.out.println(count);
A2
B3
C4
D11
Correct answer: C. "mississippi" contains two pairs of s, so the counter is increased four times.
Explanation

This is the counting pattern. The loop visits every index, extracts the one-character substring at that index, and increases count whenever the character equals "s". Comparing the extracted substring with equals is the standard way to test a single character taken from a string.

  • A is not correct: 2 counts only one of the two doubled pairs of s.
  • B is not correct: 3 leaves out one of the four matching characters.
  • D is not correct: 11 is the length of the string, which is how many times the loop runs, not how many characters match.
Q3

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

String s = "starlight";
int found = -1;

for (int i = 0; i < s.length(); i++) {
    String ch = s.substring(i, i + 1);

    if (ch.equals("t") && found == -1) {
        found = i;
    }
}

System.out.println(found);
A0
B4
C-1
D1
Correct answer: D. The test found == -1 lets only the first t be recorded, and that t sits at index 1.
Explanation

This is a search that keeps the earliest match. The second half of the condition acts as a guard: once found holds an index it is no longer -1, so a later t cannot overwrite it. The loop still runs to the end of the string, but no further assignment happens.

  • A is not correct: 0 is the index of the first character of the string, which is s, not t.
  • B is not correct: index 4 does not hold a t, so no assignment happens there.
  • C is not correct: -1 is the starting value, and it would still be printed only if the string contained no t at all.
Q4

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

String s = "planet";
String result = "";
int last = s.length() - 1;

for (int i = last; i >= 0; i -= 2) {
    result += s.substring(i, i + 1);
}

System.out.println(result);
Aplanet
Bten
Ctnl
DThe code does not compile.
Correct answer: C. Starting at the last index and subtracting two each time visits indices 5, 3, and 1, which hold t, n, and l.
Explanation

The accumulator result starts empty and grows by one character per pass. Because the loop counts down and the update subtracts two, every second index is skipped. The characters are appended in the order the loop reaches them, so the result reads from the end of the string toward the front.

  • A is not correct: planet is the whole string in its original order, which would need a forward loop with a step of one.
  • B is not correct: ten takes three neighbouring characters from the end, which is what a step of one going backward would collect.
  • D is not correct: the segment compiles; i -= 2 is a valid update expression in a for header.
Q5

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

String s = "planet";
String result = "";

for (int i = 0; i < s.length(); i += 2) {
    result += s.substring(i, i + 1);
}

System.out.println(result);
Apae
Bpnt
Clnt
Dplanet
Correct answer: A. Adding two each time visits indices 0, 2, and 4, which hold p, a, and e.
Explanation

The step in the update expression controls which indices the loop reaches. With i += 2 the loop lands on the even indices only, and the accumulator collects those characters in forward order.

  • B is not correct: pnt starts at index 0 but then takes characters at indices a step of two never reaches.
  • C is not correct: lnt holds the characters at indices 1, 3, and 5, which is what starting at index 1 would give.
  • D is not correct: planet is every character, which would need a step of one.
Q6

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

String s = "R2D2";
boolean found = false;

for (int i = 0; i < s.length(); i++) {
    String ch = s.substring(i, i + 1);

    if ("0123456789".indexOf(ch) >= 0) {
        found = true;
    }
}

System.out.println(found);
Atrue
Bfalse
C2
DR2D2
Correct answer: A. "0123456789".indexOf("2") is not negative, so found is set to true.
Explanation

Searching a string of allowed characters with indexOf is a common membership test. A non-negative result means the character was located; -1 means it was not. The flag found starts at false and is switched on by the first character that belongs to the digit string.

  • B is not correct: false is the starting value, and it would survive only if no character of s appeared among the digits.
  • C is not correct: the variable printed is found, which holds a boolean, not a digit taken from the string.
  • D is not correct: the segment prints found, not the string being examined.
Q7

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

String s = "coffeee";
int current = 1;
int longest = 1;

for (int i = 1; i < s.length(); i++) {
    String ch = s.substring(i, i + 1);
    String previous = s.substring(i - 1, i);

    if (ch.equals(previous)) {
        current++;
    } else {
        current = 1;
    }

    if (current > longest) {
        longest = current;
    }
}

System.out.println(longest);
A3
B1
C2
D4
Correct answer: A. The run of e at the end of "coffeee" reaches length 3, which is longer than the pair of f.
Explanation

Two variables cooperate here. current tracks the run that is still growing and resets to 1 whenever a character differs from its neighbour; longest keeps the largest value current has ever reached. The loop starts at index 1 so that i - 1 is always a valid index.

  • B is not correct: 1 is the starting value of longest, and it would survive only if no two neighbouring characters matched.
  • C is not correct: 2 is the length of the earlier run of f, but the later run of e grows past it.
  • D is not correct: reaching 4 would require four equal characters in a row.
Q8

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

String s = "K9-Q";
String allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        + "0123456789";
boolean valid = true;

for (int i = 0; i < s.length(); i++) {
    String ch = s.substring(i, i + 1);

    if (allowed.indexOf(ch) < 0) {
        valid = false;
    }
}

System.out.println(valid);
AK9Q4
Bfalse
CThe code does not compile.
Dtrue
Correct answer: B. The character - does not appear in allowed, so indexOf returns a negative value and valid becomes false.
Explanation

This is a validation loop. The flag valid starts at true and is switched off by the first character that fails the membership test. Because nothing switches it back on, a single disallowed character is enough to make the final result false.

  • A is not correct: the segment prints valid, a boolean, rather than a filtered copy of the string.
  • C is not correct: the segment compiles; the two string literals are joined with + before the loop begins.
  • D is not correct: true is the starting value, and it would survive only if every character of s were found in allowed.
Q9

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

String s = "cacaca";
String t = "caca";
int count = 0;
int end = s.length() - t.length();

for (int i = 0; i <= end; i++) {
    String w = s.substring(i, i + t.length());

    if (w.equals(t)) {
        count++;
    }
}

System.out.println(count);
A0
B1
C3
D2
Correct answer: D. The loop checks the windows starting at indices 0, 1, and 2, and two of them equal "caca".
Explanation

This is the sliding-window pattern for counting occurrences. Each pass takes a substring the same length as the target and compares it with equals. Because the windows advance one index at a time, occurrences that overlap are all counted.

  • A is not correct: 0 would mean no window matched, but the string begins with caca.
  • B is not correct: 1 counts only the first match and misses the overlapping one.
  • C is not correct: 3 is the number of windows the loop examines, not the number that match.
Q10

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

String result = "aababa";
String target = "aba";
int index = result.indexOf(target);

while (index >= 0) {
    result = result.substring(0, index)
             + result.substring(index + target.length());
    index = result.indexOf(target);
}

System.out.println(result);
A""
Baba
Ca
Dba
Correct answer: A. Removing the first occurrence leaves a string that still contains the target, so the loop runs again and nothing is left.
Explanation

Each pass rebuilds result from the part before the match and the part after it, which deletes exactly target.length() characters. The loop then searches the rebuilt string again. This is why removal loops must re-search after every change: deleting one occurrence can bring characters together that form a new one.

  • B is not correct: aba is what remains after the first pass, but indexOf still finds the target, so the loop does not stop there.
  • C is not correct: this keeps one character of a match, but each pass removes the whole target.
  • D is not correct: this keeps two characters of a match, but each pass removes the whole target.
Q11

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

String s = "success";
int count = 0;

for (int i = 0; i < s.length() - 1; i++) {
    String current = s.substring(i, i + 1);
    String next = s.substring(i + 1, i + 2);

    if (current.equals(next)) {
        count++;
    }
}

System.out.println(count);
A1
B2
C3
D5
Correct answer: B. "success" has two places where a character equals the one after it, so the counter reaches 2.
Explanation

Comparing neighbours means each pass needs two indices. The header stops at s.length() - 1 so that i + 1 is always a valid index; without that adjustment the last pass would ask for a character past the end of the string.

  • A is not correct: 1 counts only one of the two places where a character repeats.
  • C is not correct: reaching 3 would require a third pair of equal neighbours.
  • D is not correct: the string has only two places where a character repeats immediately, so the count cannot reach 5.
Q12

Which expression evaluates to true exactly when s1 and s2 contain the same sequence of characters?

As1 = s2
Bs1.compareTo(s2)
Cs1 == s2
Ds1.equals(s2)
Correct answer: D. equals compares the characters the two strings hold and produces a boolean.
Explanation

Comparing string contents is done with equals. This is one of the most common sources of quiet bugs, because the alternatives below all look like comparisons and some of them even compile.

  • A is not correct: a single = is assignment, not a comparison, so this does not test anything.
  • B is not correct: compareTo produces a number describing the ordering, not a boolean.
  • C is not correct: == compares the references rather than the sequence of characters they refer to.
Q13

What is the value of "library".indexOf("bra") >= 0?

Atrue
B0
Cfalse
D-1
Correct answer: A. bra occurs inside "library", so indexOf returns a non-negative index and the comparison is true.
Explanation

Comparing the result of indexOf with 0 is the usual way to ask whether one string contains another. The expression as a whole is a comparison, so its value is a boolean rather than the index itself.

  • B is not correct: >= produces a boolean, so the value of the whole expression is not an index.
  • C is not correct: false would require indexOf to return a negative value, which happens only when the target is absent.
  • D is not correct: -1 is what indexOf reports for a missing target, and it is not the value of the comparison.
Q14

Which value of s makes s.equals(reverse(s)) evaluate to true?

A"table"
B"civic"
C"paper"
D"string"
Correct answer: B. "civic" reads the same in both directions, so it equals its own reverse.
Explanation

A string equals its reverse only when reading it backward produces the same sequence of characters. Testing this with equals compares the contents, which is what the question asks about.

  • A is not correct: reversing "table" does not produce "table".
  • C is not correct: reversing "paper" does not produce "paper".
  • D is not correct: reversing "string" does not produce "string".
Q15

Consider String result = "A"; followed by String updated = result + "B";. Which statement is true?

ABoth variables store "AB".
BBoth variables store "A".
Cresult stores "AB"; updated stores "A".
Dresult stores "A"; updated stores "AB".
Correct answer: D. Concatenation builds a new string and assigns it to updated; result is never reassigned.
Explanation

Joining strings with + does not change either operand. The joined value has to be stored somewhere, and here it is stored in a separate variable, so the original keeps the value it was given.

  • A is not correct: result never appears on the left of an assignment after its declaration, so it does not change.
  • B is not correct: updated is assigned the joined value, so it does not hold "A".
  • C is not correct: this swaps the two variables; the joined value goes to updated, not to result.
Q16

Which loop header checks every possible substring of length t.length()?

Afor (int i=0; i<s.length()-t.length(); i++)
Bfor (int i=0; i<=s.length()-t.length(); i++)
Cfor (int i=0; i<t.length(); i++)
Dfor (int i=0; i<=s.length(); i++)
Correct answer: B. The last window that still fits begins at s.length() - t.length(), so the header must include that starting index.
Explanation

A sliding window needs its starting index to run from 0 through the last position where a full window still fits inside the string. Getting this bound wrong is the classic off-by-one error in substring searching.

  • A is not correct: < stops one position early, so the final window is never examined.
  • C is not correct: this counts up to the length of the target rather than to the number of possible starting positions in s.
  • D is not correct: this runs to the length of s, so windows near the end would reach past the last character.
Q17

If s is "planet", what does s.substring(2, s.length()) return?

Aane
Bnet
Canet
Dplanet
Correct answer: C. With the end index equal to s.length(), the result runs from index 2 through the last character.
Explanation

Passing the length as the end index is safe precisely because that index is excluded: the call stops after the final character rather than reaching past it. This is the idiom for taking everything from a given position to the end.

  • A is not correct: ane stops before index 5 rather than continuing to the end of the string.
  • B is not correct: net begins at index 3, one position past the start index given in the call.
  • D is not correct: planet is the whole string, which would need a start index of 0.
Q18

Which loop header can visit every valid index of s?

Afor (int i = 0; i < s.length(); i++)
Bfor (int i = 1; i <= s.length(); i++)
Cfor (int i = 0; i <= s.length(); i++)
Dfor (int i = s.length(); i > s.length(); i++)
Correct answer: A. Valid indices run from 0 up to one less than the length, which is exactly what this header visits.
Explanation

String indices are numbered from 0, so the last valid index is one less than the length. Starting at 0 and continuing while i < s.length() is the standard traversal header for that reason.

  • B is not correct: starting at 1 skips the first character, and <= reaches an index that does not exist.
  • C is not correct: <= allows i to equal the length, which is one position past the last character.
  • D is not correct: the condition is already false when the loop starts, so the body never runs.