Can you please tell me how does this java code work? :
public class Main {
public static void main (String[] args) {
Strangemethod(5);
}
public static void Strangemethod(int len) {
while(len > 1){
System.out.println(len-1);
Strangemethod(len - 1);
}
}
}
I tried to debug it and follow the code step by step but I didn't understand it.
update: sorry I didn't mention that I know the result of this code but just want to know the steps of the execution..
That'll print 4 3 2 1 1 1 1 1 1...
And get stuck in a loop because nothing ever modifies len in the scope of the while loop. The first calls (with len=5, 4, then 3) go through one loop iteration, and are left waiting for Strangemethod to return. When when len=2, the while loop calls strangemethod(1), and since len is not greater than 1, the while loop finishes and that call returns. But len is still 2 in the bottom-most remaining whle loop, so it calls strangemethod(2) again. And again. And again.
if() would've been more appropriate than while().
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