Tuesday, 8 July 2014

What is Stack and Heap in Java


Java Memory is divided into two types

  1. Stack 
  2. Heap
Both are in RAM(Random access Machine).

All objects are stored on the heap (including their attributes).
Local variables (including arguments) always contain primitive values or references and are stored on the stack.
Here is another picture below

String s = "Hello";
In this "s" are variable that hold the address/reference of "Hello" String 
Object.
Variable is on Stack and "Hello" reference is on Heap.Java only stores primitives on
 the stack and Objects are created on the heap, and only references
(which in turn are primitives) are passed around on the stack.
Let take a look on Java Code

  public class Employee{
    public static void main(String []args){
          Employee e=new Employee();
    }
  }

In above the "e" is a variable that hold the reference/address of Employee
object and "new Employee()" actually this give the reference of newly created 
object.
Variables created on the stack will go out of scope and automatically deallocate and
whether  Variables on the heap must be destroyed manually and never fall out of scope(Garbage collector/finalize() ).
In a stack of items, items sit one on top of the other in the order they were placed 
there and you can only remove the top one (without toppling the whole thing over). 
so stack follow LIFO(Last In first Out) but  In a heap, there is no particular order to the 
way items are placed.
You can reach in and remove items in any order because there is no clear 'top' item.

No comments:

Post a Comment