Java Reference
In-Depth Information
Level
Description
Relevant Code
Power(5.0, 2) {
if(n>1)
...
else
return 5.0*5.0;
}
3
Back at level 3 , the value returned,
5.0, is multiplied by the first
argument, 5.0, and returned to level
2 .
Power(5.0, 3) {
if(n > 1)
...
else
return 5.0*25.0;
}
2
Back at level 2 , the value returned,
25.0, is multiplied by the first
argument, 5.0, and returned to level
1 .
1
Power(5.0, 4) {
if(n > 1)
...
else
return 5.0*125.0;
}
Back at level 1 , the value returned,
125.0, is multiplied by the first
argument, 5.0, and 625.0 is returned
as the result of calling the method in
the first instance.
You can see from this that the method power() is called four times in all. The calls cascade down through
four levels until the value of n is such that it allows a value to be returned. The return values ripple up
through the levels until we are eventually back at the top, and 625.0 is returned to the original calling point.
As a rule, you should only use recursion where there are evident advantages in the approach, as there is
quite of lot of overhead in recursive method calls. This particular example could be more easily
programmed as a loop and it would execute much more efficiently. One example of where recursion
can be applied very effectively is in the handling of data structures such as trees. Unfortunately these
don't make convenient illustrations of how recursion works at this stage of the learning curve, because
of their complexity.
Before we can dig deeper into classes, we need to take an apparent detour to understand what a package
is in Java.
Understanding Packages
Packages are fundamental to Java programs so make sure you understand this section.
Packages are implicit in the organization of the standard classes as well as your own programs, and they
influence the names you can use for classes and the variables and methods they contain. Essentially, a
package is a unique named collection of classes. The purpose of grouping classes in a package with a
unique name is to make it easy to add any or all of the classes in a package into your program code.
One aspect of this is that the names used for classes in one package will not interfere with the names of
classes in another package, or your program, because the class names in a package are qualified by the
package name.
Search WWH ::




Custom Search