Exercise
Consider method mystery
.
public static void mystery(String str, int len)
{
if(str.length() < len)
{
System.out.print(str);
return;
}
System.out.print(str.substring(0, len));
mystery(str.substring(len), len);
System.out.print(str.substring(0, len));
}
Which of the following describes what is printed by the call below?
mystery("abcdef", 3);
(A) abcdefdefabc
(B) abcabcdefdef
(C) defabcabcdef
(D) Many values are printed because of infinite recursion.
(E) Nothing is printed because of infinite recursion.
Solution
(A) abcdefdefabc
Explanation
Infinite recursion is a possibility, so it should be addressed first. The base case is str.length() < len
. The initial call passes 3
as len
. The recursive call is made with str
without the first len
characters and the same value of len
. Repeatedly removing the first 3 characters of a string will eventually result in a string with fewer than 3 characters. The method is not infinitely recursive.
The recursive call is in the middle of two (identical) print
statements. Each print
statement prints the first len
characters of str
. The initial value of str
is abcdef
. The value of len
is 3
.
Whatever the recursive call does, the first and last values printed will be abc
(the first 3 characters of abcdef
). This eliminates all answer choices except (A).
Additional notes
The mystery
method prints groups of len
characters twice, once in their original order followed by once in reverse order.
Additional calls to the method are below.
mystery("abcdef", 2);
prints abcdefefcdab
mystery("abcdefg", 2);
prints abcdefgefcdab
Help & comments
Get help from AP CS Tutor Brandon Horn