Q:

Recursion using global variable in java

How do global variables work in case of recursion functions?
I have a code below. Why does this prints 7 0's as output?
int giValue=6;
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Demo obj1=new Demo();
    obj1.fnReverse();
}

public void fnReverse(){
    if(giValue>0){
        giValue--;
        fnReverse();
    }
    System.out.println(" "+giValue);
}

I would like to know where the global variable value is getting saved, and how the value is changing?
Thanks

A:

It prints 7 zeroes because at the end of each recursive call you are printing the value of giValue. Since the method never reaches the print statement until giValue reaches 0, it prints only 0s when the recursion unwinds.
The value is changing due to the giValue--; line. giValue is not a global variable. It's an instance variable of your Demo class, and its value is initialized to 6 when you create the Demo instance.
There are 7 calls to the method - the initial call and 6 additional recursive calls. The first 6 calls decrement giValue, so during the 7th call its value is 0 and the recursion ends.

