There are two area inside java virtual machine's memory the heap and the stack. The stack memory is used to store local variables and function call while heap memory is used to store objects in Java
The most common cause of StackOverFlowError is too deep or infinite recursion or many local objects / variables creation inside function call in Java.
According to the java source documentation, Java throws java.lang.StackOverflowError when a stack overflow occurs because an application recurses too deeply.
JVM has a given memory allocation for each stack of each thread, and if an attempt to call a method happens to fill this memory, JVM throws an error. Just like it would do if we try to write at index N of an array of length N.
The point to be noted here is that -
- These are errors not an exceptions.
- No memory corruption happens due to the error.
- Stack can not write into the heap space.
A StackOverflowError is related to the stack memory and OutOfMemoryError is related to the heap space. it simply refers that there is no more memory available.
Below are sample examples code which will throw this error -
public class StackOverflowErrorExample {
public static void recursivePrint(int num) {
System.out.println("Number: " + num);
if(num == 0)
return;
else
recursivePrint(++num);
}
public static void main(String[] args) {
StackOverflowErrorExample.recursivePrint(1);
}
}
public class StackOverFlowExample {
StackOverFlowExample test = new StackOverFlowExample();
public static void main(String[] args) {
new StackOverFlowExample();
}
}
Comments
Post a Comment