1

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);
    }
}
sandejai
  • 931
  • 1
  • 15
  • 22
  • 2
    Java does not do any code optimization for tail recursion: http://stackoverflow.com/questions/3616483/why-does-the-jvm-still-not-support-tail-call-optimization – Tunaki Sep 27 '15 at 15:23

1 Answers1

2

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!