Can anybody tell me what is StackOverflowError in Java ?
Usually when recursive method is being called too many times. For example:
public void doSomething(int time)
{
System.out.println("do #" + (doSomething(time++)));
}
A stack overflow occurs when too much data is put on the stack, which is a limited resource.
Here's an example:
public class Overflow {
public static final void main(String[] args) {
main(args);
}
}
That function calls itself repeatedly with no termination condition. Consequently, the stack fills up because each call has to push a return address on the stack, but the return addresses are never popped off the stack because the function never returns, it just keeps calling itself.
There is no such thing as a StackOverFlowException
in Java.
There is, however, a class named StackOverflowError
and the documentation says:
Thrown when a stack overflow occurs because an application recurses too deeply.
If you don't know what the stack is, read this: Call stack
Each time you call a function, a small piece of a special memory region - the stack - is allocated to it and holds the local variables and the context of the function. If our function calls another function, the next piece is cut off the stack and so on. The stack shrinks when a function returns again. If the nesting level becomes too high, it can overflow.
This is a very general concept. On Java, a StackOverflowError
is thrown when the stack size is exceeded. This is an error, not an exception, because you are urged to avoid this situation, not recover from it.
The typical example would be endless recursion:
public void foo(int i) {
return foo(i+1);
}
The Java machine allocates your program a specific quantity of memory. The error is caused by your program using too much memory. The examples above are good, but if you are trying to create a very large array that can cause it to overflow as well. You can Allocate more memory(this example of 200MB) to your program by using command line arguments
java -Xmx200m YOUR_PROGRAM_CLASS
This will decrease the chance of you getting a StackOverFlowException.
This Explains the command line options
(http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/java.html#Xms)