go to previous page   go to home page   go to next page

Answer:

str.substring(1)

creates a substring that contains all the characters from str from character 1 to the end.


Java Implementation

public class StringTester
{
  public static int length( String str )
  {
    if ( str.isEmpty() ) 
      return 0;
    else
      return 1 + length( str.substring(1) );
  }
   
  public static void main (String[] args)
  {
    String snake = "rattlesnake";
    
    System.out.println( "Length of " + snake + " is: " + length( snake ) );
  }
}

We now have all the pieces needed to complete the method. Study how length() fits the recursive definition:

  1. If a string is empty, then its length is 0.
  2. Otherwise,
    • the length of the string is 1 + length of the tail
    • The expression str.substring(1) is the tail of the string.
    • The expression length( str.substring(1) ) is the length of the tail.

Recall that in Java the index of the first character of a string is 0, so that the str.substring(1) gives you all the characters of the string starting with the character after the first.

However: if the string has only one character in it, then str.substring(1) gives you an empty string. (So the tail of a one-character string is the empty string.)

Note to AP students: the above odd fact has sometimes been needed for the free response part of the AP test.


QUESTION 8:

In computing the length (11) of the example, how many objects were created by the length() method?


go to previous page   go to home page   go to next page