If you're using IDE you can just use the debugger and see with you own eyes what's happening step by step.
Anyway, let's try and what happens when we call the recursive method:
You call the method with 8 (printit(8);
):
System.out.println(8);
-> 8
printit(8 /2 );
-> Call to method again with 8/2=4
System.out.println(4);
-> 4
printit(4 /2 );
> Call to method again with 4/2=2
System.out.println(2);
-> 2
printit(2 /2 );
> Call to method again with 2/2=1
return;
-> Continues with previous call, the (printit(4 /2);
)
printit(2 /2 );
> Call to method again with 2/2=1
return;
-> Continues with previous call, the (printit(4 /2);
)
- method finishes, continues with the previous call (
printit(8 /2);
)
printit(4 /2 );
> Call to method again with 4/2=2
System.out.println(2);
-> 2
- calls
printit(2/2);
which we already know result in nothing.
- Now we are in the first call again, the
printit(8);
, calling for printit(8/2);
System.out.println(4);
-> 4
- 16 etc...