Friday, 4 July 2014

Stack Versus Heap in Java


Difference between Stack and Heap memory in Java

Stack - 

          Stack is a memory area where we store local variables , function calls,current location of execution i .e .Program Counter value.
        Stack follows the procedure of First In Last Out (FILO)i.e.  object/function call that is last inserted into stack will be taken first for further execution . 
     e.g 
          void a(){
                    b();
                    c();
         }

     In this case the stack will contain the following things - 



       On completion of c it will start executing b from the point it left and finally a will execute after b completes its execution.

Heap  - 

          Heap is a memory area where we store objects created by the program.


void somefunction( )
{
/* create an object "m" of class Member
    this will be put on the heap since the 
    "new" keyword is used, and we are 
   creating the object inside a function
*/
  
  Member m = new Member( ) ;
  
  /* the object "m" must be deleted
      otherwise a memory leak occurs
  */

 
} 


This will create an object on the heap.




   

No comments: