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

Answer:

If str refers to an empty String object

str.equals("")  is true, because both objects contain the same characters.

However,

str == ""  is almost always false, 

because the reference variable str almost always refers to a different object than the particular object "". (Review Chapter 27 if this is unclear.)


The Rest of the String

So far the method looks like this:

static int length( String str )
{
  if ( str.isEmpty() )           // or use str.equals("")
    return 0;
  
  else
    return 1 + length of all but first character of str;
}

But now there is another problem: How can you compute the length of all but the first character of the string?

This can be done by:

  1. Create a substring that omits the first character.
    • recall that the first character of a string is at position 0
  2. Use length() on that substring


QUESTION 7:

(Review: ) What does this do:

str.substring(1)

Assume str refers to a String object.