java.lang.StackOverFlowError versus java.lang.OutOfMemoryError

The difference between StackOverFlowError  and OutOfMemoryError is a very common question among folks who are beginners in java. The topic is more of understanding the difference between Heap and Stack.

Stack, as you might have heard of during your college times is LIFO (Last In First Out). Now this sounds very bookish. It doesn't clarify why do we have it actually in java. And when does it fill up completely to throw StackOverFlowError.

To make it clear, Stack and Heap are part of memory allocated to a program and is used for different purpose.When a java program runs inside JVM, it uses both for different needs.

1. Stack memory is used to store local variables and function calls. On the other hand heap memory is used to store objects in Java. No matter, where object is created in code e.g. as member variable, local variable or class variable,  they are always created inside heap space in Java. Heap size is very very larger compared to Stack size as variables and function calls require lesser space compared to objects.

2. If there is no memory left in stack for storing function call or local variable, JVM throws java.lang.StackOverFlowError.
And if there is no more heap space for creating an object, JVM throws java.lang.OutOfMemoryError:

3. When we use recursion where a function calls itself over and again, this stack fills up very quickly and throws StackOverFlowError.

4. The variables stored in stacks are only visible to the owner Thread. On the other hand, the objects created in heap are visible to all threads.

No comments :

Post a Comment

Recent Posts