When I tried to run this program couple of times the final value of i
is 11407
, 11417
, 11400
etc. before displaying stack overflow error. Why is the final value of i
not same every time this program is executed?
public class MainRecursive {
static int i=0;
public static void main (String arg[])
{
i++;
System.out.println(i);
main(arg);
}
}
The args defined in your field isn't going to be regarded as the same args you're attempting to recursively call in main . Second, the recursion eventually runs out, but that's dependent on how much memory you have allocated for the application, and what else is in memory at the time.
The main() function can call itself in C++. This is an example of recursion as that means a function calling itself.
In Java, a method that calls itself is known as a recursive method. And, this process is known as recursion. A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.
Try to add System.out.flush();
after printing.
Since the stack size is not changing, i gets to the same value each time you run, but I think println()
gets interrupted by the exception before it updates the output at different times - this depends on the console, operating system etc and cannot be deterministic.
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