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

Answer:

Yes.


Two Parts in One Statement

Now look at the parts 2 and 3 of the recursive definition:

  1. If StringA has no characters and StringB has no characters, then the strings ARE equal.
  2. If StringA has no characters and StringB has some characters, then the strings are NOT equal.
  3. If StringA has some characters and StringB has no characters, then the strings are NOT equal.
  4. ...

The Java code is a little bit tricky:

if ( strA.isEmpty() && strB.isEmpty() ) 
  return true;
else if ( strA.isEmpty() || strB.isEmpty() ) 
  return false;
...

Rules 2 and 3 say to return false if one string is empty but the other string is not. This is what the Java code does. The first if returns true if both strings are empty. So the else if is executed only when at least one string has characters in it. If the other string is empty, the strings are not equal (so return false).


QUESTION 21:

Does this Java code:

   else if ( strA.charAt(0) != strB.charAt(0) )
      return false;
   else
      return myEquals( strA.substring(1), strB.substring(1));

correctly implement the rule

  1. Otherwise,
    • if the first character of StringA is different from the first character of StringB, then the strings are NOT equal.
    • if the first character of StringA is the same the first character of StringB, then the strings are equal if the tails ARE equal.

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