String Loop AP CS A Practice Multiple Choose Question

Below is an AP styled multiple choice question involving involving a while loop over a string and the indexOf() method.

What is the result of the call to the method mystery(“xyaxy__x_yxy”,”xy”)

  1. ArrayIndexOutOfBounds  Error
  2. returns 1
  3. infinite loop
  4. returns 3
  5. returns 2

 

  public int mystery(String str, String s2)
       {
        int r =0;
        while (str.indexOf(s2) >  -1 )
            {
           r++;
           str = str.substring(str.indexOf(s2) +  s2.length() ) ;
          }
        return r;
        }


 

Scroll down  for answer.

 

The answer is

  1. ArrayIndexOutOfBounds  Error
  2. returns 1
  3. infinite loop
  4. returns 3
  5. returns 2

This method does not go out of bounds. This method counts up how many times s2  occurs in str  by resizing the string using indexOf()  and substring()  .