简体   繁体   中英

Java tail recursion : Is below Fibonacci code tail recursive ?

I recently learnt about tail recursion. I understand, many programming language compilers perform[Current java doesn't] s, code optimization when it finds a recursive method a "Tail recursive".

My understanding of TR : Compiler, does not create new stack frame(instead replace with older call's stack frame) when there is no further operation to be performed after the call has returned.

Is below code[ even though in java] a tail recursive ?

suppose totalSeriesLenght = 10.

public void generateFibonacciSeries(int totalSeriesLenght) {
    int firstNum = 0;
    int secondNum = 1;
    printNextFibonacciNumber(firstNum, secondNum,totalSeriesLenght);
}

public void  printNextFibonacciNumber(int fiboOne , int fiboTwo,int totalSeriesLenght) {
    if(totalSeriesLenght >= 1) {
        System.out.print(fiboOne + ",");
        int fiboNext = fiboOne + fiboTwo;           
        totalSeriesLenght --;
        printNextFibonacciNumber(fiboTwo, fiboNext,totalSeriesLenght);
    }
}

Yes the function call is tail-recursive, but Java does not have any tail call optimization, so new stack frames will be created.

As proof consider the following program:

public class Test{
  public static void main(String[] args){
    recursive();
  }

  public static void recursive(){
    recursive();
  }
}

running this program results in a StackOverflowError which means that the stack had to be filled with something: stack frames!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM