Posts

Showing posts from April, 2017

Memory Management in Java - Stack and Heap

Image
Memory Management in Java - Stack and Heap  Memory management is a mechanism to allocate memory when new objects are created and free it when no longer needed. In Java, the memory is divided into 2 segments: STACK HEAP STACK The stack is the place where any local variables and methods are stored. The lifetime of variables on the stack is governed by the scope of the code . The scope is usually defined by an area of code in curly brackets, such as a method call, or for or while loop. Once the execution has left that scope, those variables declared in the scope are removed from the stack. When the stack memory fills up, and eventually any more method calls will not be able to allocate their necessary variables. This results in a StackOverflowError . HEAP The heap is the place where objects, instance variables and static variables are stored. The new keyword allocates memory on the Java heap. The heap is the main pool of memory, accessible to t