A program that displays a trace feature of a recursive method call
This program is a part of the companion code for Core Java 8th ed.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
* A program that displays a trace feature of a recursive method call.
* @version 1.01 2004-05-10
* @author Cay Horstmann
public class StackTraceTest
* Computes the factorial of a number
* @param n a nonnegative integer
* @return n! = 1 * 2 * . . . * n
public static int factorial(int n)
System.out.println("factorial(" + n + "):");
Throwable t = new Throwable();
StackTraceElement frames = t.getStackTrace();
for (StackTraceElement f : frames)
if (n <= 1) r = 1;
else r = n * factorial(n - 1);
System.out.println("return " + r);
public static void main(String args)
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
Related examples in the same category