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

Answer:

11


Horribly Inefficient

Each recursive call

return 1 + length( str.substring(1) )

uses substring() to create a new object. Object creation is complicated. Luckily for us, the Java system handles that behind the scenes. However, creating all these extra objects, which then immediately become garbage, takes time.

The actual length() method does something more efficient. If you need speed, you would likely use a StringBuffer and iteration. But our job here is to study recursion, not to worry about efficiency.

Our length() can be used as a model for some methods that are not included in String and which you might wish to write recursively. (See the exercises.) Sometimes a recursive method is short and clear, where the efficient method is complicated and unclear.


QUESTION 9:

How many of X are in the string "XabcaXvw, tuwXcbXXXw, qityrsmnX; XXX123eryiop[X]" ?

Hint: there are 10 characters X in the tail of the string.


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