Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is main method not getting called same no. of times recursively in java every time it is executed?

Tags:

java

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);
    }
}
like image 872
Uma Kalyani Avatar asked Nov 06 '14 09:11

Uma Kalyani


People also ask

Can main function be called recursively in Java?

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.

Can main method be recursive?

The main() function can call itself in C++. This is an example of recursion as that means a function calling itself.

Can a method call itself in Java?

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.


1 Answers

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.

like image 99
coyote Avatar answered Oct 21 '22 04:10

coyote