Exercise

Consider method mystery.

public static void mystery(String str)
{
    if(str.length() < 3)
    {
        return;
    }
    
    mystery(str.substring(3) + str.substring(0, 3));
    System.out.println(str.substring(0, 3));
}

Which of the following describes what is printed by the call below?

mystery("abcdefhig");

(A) higdefabc
(B) abcdefhig
(C) abcdefhighigdefabc
(D) Many values are printed because of infinite recursion.
(E) Nothing is printed because of infinite recursion.

Solution

(E) Nothing is printed because of infinite recursion.

Explanation

The base case is str.length() < 3. The recursive call passes a string of the same length. This does not get closer to the base case. The method is infinitely recursive.

The println statement is after the recursive call. Since the method is infinitely recursive, none of the recursive calls return. The print statement is never reached.

Not every infinitely recursive method with a print statement actually prints something.

Additional notes

str.substring(3) returns everything except the first 3 characters of str.

str.substring(0, 3) returns the first 3 characters of str.

See Strings on the AP CS A Exam.

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on Recursive methods with print statements