Tuesday 16 April 2013

What is Stack and Heap in java? What is the main difference between them?




Stack: A stack follows the LIFO-queue rule means that the last data to be inserted will be the first data to be removed. When we insert data into a stack, it is placed at the head of a queue. This means that when we remove data, it will be in reverse order. Adding 1,2,3,4 will return 4,3,2,1.
 Stacks aren't the most frequently used data structure, but they are extremely useful for certain tasks. To understand it more clearly, Please look into the below example

Example of Stack

import java.util.*;

public class demoCollection3
{
    public static void main(String s[])
    {
        Stack st = new Stack();
        st.push("Java");
        st.push("is");
        st.push("number");
        st.push("one");
        Iterator it = st.iterator();
        while(it.hasNext())
        {
        System.out.println(it.next());
        }
        System.out.println("The element removed  is : - "+st.pop()); //Remove the last element added(LIFO)
        System.out.println("Now the Stack is : - "+st);
    }
}

Queue: A queue follows the FIFO-queue rule means that the first data to be inserted will be the first data to be removed. Suppose we add 1,2,3,4 and then we remove, the first element (1) will be removed (Please refer below example).
  
Example of Queue

import java.util.*;
public class demoCollection4
{
    public static void main(String s[])
        {
            Queue st = new LinkedList();//Cannot initiate Queue beacause it is abstract so this is implemented with LinkedList
            st.add("Java");
            st.add("is");
            st.add("number");
            st.add("one");

            System.out.println(st.poll());//Remove the First element added(FIFO)
            System.out.println(st);
        }
}




                                              Use of Stack and Queue in java?

The Heap is used to store object and global variable and stack  is used to store local variable, function cal etc.
The main difference is that stack will deallocate the variable as soon as they are out of scope or functions and methods don’t need them more but heap will keep them for longer time.
Stack storage is faster than Heap storage.

If stack is full it will throw java.lang.StackOverFlowError and if Heap is full it will throw java.lang.OutOfMemoryError

1 comment: