views:

202

answers:

5

Can anybody tell me what is StackOverflowError in Java ?

A: 

Usually when recursive method is being called too many times. For example:

public void doSomething(int time)
{
  System.out.println("do #" + (doSomething(time++)));
}
Boris Pavlović
+11  A: 

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.

T.J. Crowder
+7  A: 

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

Jesper
@Don: Don't delete part of my answer please. I've rolled back your deletion.
Jesper
@Jesper - I deleted it because I also changed the question so that part of your answer didn't make sense anymore
Don
+2  A: 

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);
}
Alexander Gessler
A: 

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)

Lee
-1: StackOverflowError can occur even if there is lot of heap memory
Santhosh Kumar T
however the root cause of the error is still the same, too much memory. you can either solve it by increasing the heap size or changing your program to use the memory more effectively.
Lee