Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

recursion - In a recursive statment, how does java store the past values?

public class Factorial {
int factR(int n){
    int result;
    if(n==1)return 1;
    result=factR(n-1)*n;
    System.out.println("Recursion"+result);
    return result;
}

I know that this method will have the output of

  Recursion2
  Recursion6
  Recursion24
  Recursion120
  Recursive120

However, my question is how does java store the past values for the factorial? It also appears as if java decides to multiply the values from the bottom up. What is the process by which this occurs? It it due to how java stores memory in its stack?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

http://www.programmerinterview.com/index.php/recursion/explanation-of-recursion/

The values are stored on Java's call stack. It's in reverse because of how this recursive function is defined. You're getting n, then multiplying it by the value from the same function for n-1 and so on, and so on, until it reaches 1 and just returns 1 at that level. So, for 5, it would be 5 * 4 * 3 * 2 * 1. Answer is the same regardless of the direction of multiplication.

You can see how this works by writing a program that will break the stack and give you a StackOverflowError. You cannot store infinite state on the call stack!

public class StackTest {
    public static void main(String[] args) {
        run(1);
    }

    private static void run(int index) {
        System.out.println("Index: " + index);
        run(++index);
    }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...