Search code examples
javarecursionstack-overflow

Why does this Java class give a stack overflow exception?


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);

    }

}

Solution

  • 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.