What is StackOverflowError in Java with Example

StackOverflowError will be Thrown when a stack overflow occurs because an application recurses too deeply. A stack overflow is usually called by nesting function calls too deeply (especially easy when using recursion, i.e. a function that calls itself) or allocating a large amount of memory on the stack where using the heap would be more appropriate.

For Example if you have code like:

package Com.javatechinfo;

public class StackOverflowExample {

/**
* @param args
*/
public static void main(String[] args) {

new StackOverflowExample().overflowTest();
}

void overflowTest() {
// some code ...

overflowTest(); // This will throw StackOverflowError
}


}

Then overflowTest( ) will keep calling itself, getting deeper and deeper, and when the space used to keep track of what methods you're in is filled up, you get the stack overflow error.


Output:

Exception in thread "main" java.lang.StackOverflowError
at Com.javatechinfo.StackOverflowExample.overflowTest(StackOverflowExample.java:16)
at Com.javatechinfo.StackOverflowExample.overflowTest(StackOverflowExample.java:16)
at Com.javatechinfo.StackOverflowExample.overflowTest(StackOverflowExample.java:16)

Search: