StackOverflowError vs OutOfMemoryError in Java

[3324 views]




To run a Java program, memory is required. This memory is allocated from the Operating System to JVM (Java Virtual Machine)and is divided into two parts, namely:

  1. Stack memory
  2. Heap memory

Stack Memory

Stack memory is used when we call a method or run some thread. As we keep on calling methods, Present state of program and local variables are pushed to the stack memory. Once method is finished, its local variables are popped from the stack memory.

public class test{ static void innerMethod(int i){ System.out.println(i); } static void outerMethod(String str, int i){ innerMethod(i); System.out.println(str); } public static void main(String[] args){ outerMethod("Print me !!", 10); } }

Here's the corresponding call stack. SP denotes the Stack Pointer.

call stack in Stack memory

Heap Memory

Heap memory is used when we declare and initialize an object. This object can be an array, variable, constant, etc.

StackOverflowError vs OutOfMemoryError:

The memory provided by the operating system to run the Java program is limited, and so are Stack and Heap memory.

java.lang.stackOverflowError is raised when we run out of Stack memory. This can arise when we call a recursive method without proper terminating condition. If we keep on calling methods, state information keeps adding to the call stack, the Stack memory runs out of space. Here's an example of code which will throw this error.

public class stackOverflowExample{ private static void printFunction(int i){ printFunction(i+1); System.out.println(i); } public static void main(String[] args){ printFunction(0); } }

To remove this error, proper terminating condition can be written. Lets add a terminating condition to the previous code snippet:

public class stackOverflowExample{ private static void printFunction(int i){ if(i==10)return; //Terminating Condition printFunction(i+1); System.out.println(i); } public static void main(String[] args){ printFunction(0); } }

java.lang.outOfMemoryError is raised when we run out of Heap memory and memory isn't available for new Objects. This arises when we have live references to our object or we try to create a very large object. If an object has live reference, Garbage Collector doesn't remove it. Here's an example of outOfMemoryError.

public class outOfMemoryErrorExample{ public static void main(String[] args){ int[] integerArray = new int[1024*1024*1024]; } }

To remove this error, make sure that you don't allocate large space to objects like in the above example and there are no live references to the objects.

                 



Clear Any Java Interview by Reading our Ebook Once.


Can you clear Java Interview?




Comments










Search Anything:

Sponsored Deals ends in





Technical Quizzes Specially For You:

Search Tags