What is the output of the following program?
public class whatever {
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int n){
if (n>0){
xMethod(n-1);
System.out.print(n + " ");
}
}
}
main
xMethod(5)
xMethod(4)
xMethod(3)
xMethod(2)
xMethod(1)
xMethod(0)
print 1
print 2
print 3
print 4
print 5
So you see the prints are 1,2,3,4,5
System.out.print(n + " ");
xMethod(n-1);
It will print 5 4 3 2 1. Because It will first print then call xMethod.
And in your case
xMethod(n-1);
System.out.print(n + " ");
Here it will reach to end condition then poped up and print. so 1 2 3 4 5
Please read original article at Java - Understanding Recursion