Java Reference

In-Depth Information

Caution
Youcannotusethisformofthereturnstatementinaconstructorbecause

constructors do not have return types.

Invoking Methods Recursively

Amethodnormallyexecutesstatementsthatmayincludecallstoothermethods,suchas

printDetails()
invoking
System.out.println()
. However, it is occasion-

ally convenient to have a method call itself. This scenario is known as
recursion
.

Forexample,supposeyouneedtowriteamethodthatreturnsa
factorial
(theproduct

ofallthepositiveintegersuptoandincludingaspecificinteger).Forexample,3!(the!

is the mathematical symbol for factorial) equals 3×2×1 or 6.

Yourfirstapproachtowritingthismethodmightconsistofthecodepresentedinthe

following example:

int factorial(int n)

{

int product = 1;

for (int i = 2; i <= n; i++)

product *= i;

return product;

}

Although this code accomplishes its task (via iteration),
factorial()
could also

be written according to the following example's recursive style.

int factorial(int n)

{

if (n == 1)

return 1; // base problem

else

return n*factorial(n-1);

}

Therecursiveapproachtakesadvantageofbeingabletoexpressaprobleminsimpler

termsofitself.Accordingtothisexample,thesimplestproblem,whichisalsoknownas

the
base problem
, is 1! (1).

Whenanargumentgreaterthan1ispassedto
factorial()
,thismethodbreaksthe

problemintoasimplerproblembycallingitselfwiththenextsmallerargumentvalue.

Eventually, the base problem will be reached.

For example, calling
factorial(4)
results in the following stack of expressions: