I researched a bit further and thus I will rewrite my question further more clearly so that people can understand where my concern is.
# Title: Recursive function and call stack: Basic to Advanced understanding required!
I was solving this particular problem from the textbook in the journey of self-learning.
Trace and Find the output.
package com.example.demo;
public class Testy {
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int n) {
if (n > 0) {
System.out.println(n + " ");
xMethod(n - 1);
}
}
}
This was insanely easy for me to grasp. First I will print 5 then call xMethod(4).
Next time, I will then print 4 then call xMethod(3)
And so on.
The output will be 5,4,3,2,1.
The previous question was twisted by a bit. Like this:
package com.example.demo;
public class Testy {
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int n) {
if (n > 0) {
xMethod(n - 1);
System.out.println(n + " ");
}
}
}
I thought OK Fine. I will now just decrement n before printing, that is all. And got 4,3,2,1,0 as my expected hand traced output. Poor me, I was very wrong.
The output is 1,2,3,4,5.
Based on the solution, I can (obviously) see a stack is being used.
I do not see a reason why the print function should execute in the second case.
Once we call xMethod(1) then We will call xMethod(0). Now in next iteration we are at base case as n no more is greater than zero.
Since nothing is specified for base case, I assume it will simply return (return what i do not know maybe that is the source of the entire confusion) back.
We have started popping now the if(n>0) should no more execute. Hence, print function should no more execute. This is my concern.
I hope I am clear.
# Edit 2
Based on further research, it seems to be that once xMethod(0) is executed, we execute print function.
Let's say xMethod(0) returns to xMethod(1) Nothing. But the return should be happening all at once (without executing the print function is what I feel). So, x(1) returns nothing to x(2).......and so on till x(4) returns nothing to x(5). Finally the print function should be executed. But if that is the case, how will the n values be stored? Because stack has already been popped by now. How will the program remember the values that were already popped from stack?
This leads me to believe the most possible thing. Popping and printing happens one after another instead. But why? I do not understand that. I am not seeking some deep level stuff, but simple logic and understanding is fine.