Java Reference
In-Depth Information
4*factorial(3)
3*factorial(2)
2*factorial(1)
Thislastexpressionisatthetopofthestack.When
factorial(1)
returns1,these
expressions are evaluated as the stack begins to unwind:
•
2*factorial(1)
now becomes 2*1 (2)
•
3*factorial(2)
now becomes 3*2 (6)
•
4*factorial(3)
now becomes 4*6 (24)
Recursion provides an elegant way to express many problems. Additional examples
includesearchingtree-baseddatastructuresforspecificvaluesand,inahierarchicalfile
system, finding and outputting the names of all files that contain specific text.
Caution
Recursionconsumesstackspace,somakesurethatyourrecursioneventu-
allyendsinabaseproblem;otherwise,youwillrunoutofstackspaceandyourapplic-
ation will be forced to terminate.
Overloading Methods
Java lets you introduce methods with the same name but different parameter lists into
the same class. This feature is known as
method overloading
. When the compiler en-
countersamethodinvocationexpression,itcomparesthecalledmethod'sargumentslist
with each overloaded method's parameter list as it looks for the correct method to in-
voke.
Twosame-namedmethodsareoverloadedwhentheirparameterlistsdifferinnumber
or order of parameters. For example, Java's
String
class provides overloaded
pub-
lic int indexOf(int ch)
and
public int indexOf(int ch, int
fromIndex)
methods.Thesemethodsdifferinparametercounts.(Iexplore
String
Twosame-namedmethodsareoverloadedwhenatleastoneparameterdiffersintype.
Forexample,Java's
java.lang.Math
classprovidesoverloaded
public static
double abs(double a)
and
public static int abs(int a)
methods.
Onemethod'sparameter isa
double
;theothermethod'sparameter isan
int
.(Iex-
You cannot overload a method by changing only the return type. For example,
double sum(double... values)
and
int sum(double... values)
are
notoverloaded.Thesemethodsarenotoverloadedbecausethecompilerdoesnothave