javarecursionobjectinstantiation

Local variable in recursion retaining values?


Currently working on recursion practice/implementation and noticed something that goes against everything I know to be true in programming.

Recursive method

protected int getArea() {

    if(width <= 0)
        return 0;
    else if(width == 1)
        return 1;
    else {

        Triangle t2 = new Triangle(width - 1);
        int area = t2.getArea();//Area variable somehow is holding the values of previous calls, despite being instantiated in each new call?

        return area + width;

    }

}

Somehow, the local variable, area, is aggregating values from previous calls in the recursive method. How is this possible, when with each call it is instantiated? In each call, it appears the method getArea() is called again, preventing the area variable from holding anything due to the fact the getArea() call happens before the methods return statement.

How is this happening?


Solution

  • Each method call details are stored on stack, once the value is returned from the method call the execution returns to the previous method calling the current method, the local variable values,etc,. would be stored on the stack and that's how those values are used in the execution when required by program. Do some experimentation around recursive programs to understand more about it.

    My suggestion would be try debugging recursive programs using break points on IDE's like eclipse or Intellij, it would clear a lot of confusion and brings clarity on how recursion works.