-2

This is a simple java class calls the main method recursively, but it throws a stack overflow exception. How does the stack overflow exception occur?

public class NewClass {

    public static void main(String args[]) {

        main(args);

    }

}
WillS
  • 362
  • 1
  • 12
Gihan
  • 11
  • 3

4 Answers4

2

That's what happens when a method calls itself recursively infinite number of times. Each call creates a new stack frame, until the stack overflows.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • I also thought like that. But after running following code i confused again public class NewClass { public static void main(String args[]) { while (true) { m(); } } static void m() { } } //this code run without exception – Gihan Mar 16 '15 at 07:24
  • @Gihan Why did you get confused? You should realize that each new call to main is made before the previous call returns, which means no call ever returns, which means the stack keeps growing until the overflow occurs. – Eran Mar 16 '15 at 07:26
0

Because you are calling the main method which is calling the main method which is calling the main method - forever - until it crashes.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • The thing that i don't understand is why its crashes. because its only calling method again and again. Is that make objects and fill the stack of the jvm..? – Gihan Mar 16 '15 at 07:20
  • Imagine the JVM calling some code, when it finishes, it needs to know where to go back to. Of course this information needs to be kept track of. The space that is used to keep track of this is running out, and that is why you get a StackOverFlow error – Scary Wombat Mar 16 '15 at 07:22
0

You are caliing main recursively without any exit condition. So, with each method call, a stack frame is created adn there is only finite memory and thus it is bound to be overflown with continuous frame creation. Have some exit condition, then it will run fine.

Tarun
  • 184
  • 6
  • Memory constraint will always be there so even if there is exit condition but the exit condition will become true after lot of stack frame creation, it will again throw the stack overflow error. Use recursive function wisely. – Tarun Mar 16 '15 at 07:16
0

When You call a method JVM Keeps it in a stack (Stack size is Limited and depends on your JRE configuration). At first main method will be called and it will get loaded in Stack and then it will again call main method which will again come to stack... like wise for every call the method will be loaded in stack till the called method (Here main()) will return the control to its the calling method(Again main()). Since The system memory is limited at some point of time stack will be full and at that point of time JVM will raise an StackOverFlowError.

Animesh Agrawal
  • 161
  • 2
  • 16