What\'s the difference between StackOverflowError and OutOfMemoryError and how to avoid them in application?
Imagine you have a function like the following
public void f(int x) {
return f(x + 1);
}
When you'll call it the call will call f again and again and again. At each call a bit of information is stored on the stack. Since the stack is limited in size you will get a StackOverflowError.
Now imagine the following code:
for (int i = 1; i > 0; i++)
vector.add(new BigObject());
where BigObject is a normal Java object. As you see, the loop never terminates. Each allocation is done on the heap thus it will be filled with BigObjects and you will get an OutOfMemoryError.
To recap:
OutOfMemoryError is thrown when you are creating objectsStackOverflowError is thrown when you are calling functions