I'm new to java and I was studying some articles about Recursion when I stumbled upon this little program which I don't understand.
static void print(int i) {
if ( i > 1) {
System.out.print("Y");
print(i-1);
}
for (int t = 0; t < i ; t++)
System.out.print(i); // i not t
}
When I do print(4) the outcome is YYY1223334444 but why isn't it YYY1? I don't get that part.
The answer provided by Gerald Mücke is the best approach: roll out the code and see in what order the methods are actually called. What is important to know is that the recursive print(i-1) call is blocking. It will wait until its invocation has returned before it continues onto the the next statement, which is the for loop. This means that by the time you get to the call where the i argument is 1, you are 4 calls deep: print(4) -> print(3) -> print(2) -> print(1). This is why people speak of a "call stack" and why you get a stack trace if you output an exception. Oh, and why you get the stackoverflow error that this very site is called after if your call stack goes so deep (for example, recursion without an end condition) that it exceeds a certain value.
While Gerald typed his answer I was making a visual representation that might help you undestand better. The colored blocks are method invocations, with nesting showing how they sit on top one another in the call stack, and arrows for the program's statement flow.

Let's roll out the ifs, recursion and the loop. What the system does its:
print(i=4) {
System.out.print("Y") -> Y
print(i=3) {
System.out.print("Y") -> YY
print(i=2){
System.out.print("Y") -> YYY
print(i=1){
//skip if and print 1x i=1
System.out.print(1) -> YYY1
}
//print 2x i=2
System.out.print(2) -> YYY12
System.out.print(2) -> YYY122
}
//print 3x i=3
System.out.print(3) -> YYY1223
System.out.print(3) -> YYY12233
System.out.print(3) -> YYY122333
}
//print 4x i=4
System.out.print(4) -> YYY1223334
System.out.print(4) -> YYY12233344
System.out.print(4) -> YYY122333444
System.out.print(4) -> YYY1223334444
}
The code deos not return after the if but execute the for loop.
If you're new to Java, make yourself familiar with a debugger, which allows a step-by-step execution and value introspection and is part of every Java IDE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With