about Heap and Stack Memory in Java

Stack  Memory Allocation and Heap Memory Allocation

In Java Virtual Machine, There are two type of memory allocation process.
1)Stack  Memory Allocation
2)Heap Memory Allocation

Stack  Memory Allocation -
           When ever any class will be written in java, this files content will goes in the  Stack  Memory Allocation area.

    Example:-

           class TestA{
        int x=10;
        int y=20
   
        public int add(int x, int y){
        return x+y;   
        }
    }

    The class A will be stored in Stack  Memory Allocation area.

Heap Memory Allocation -
    When ever object of any class will be made then this object will be stored in Heap Memory Allocation area.

    Example :-
            If  we are making the object of the above class
   
    new TestA();

    then this object will stored in Heap Memory Allocation area.

Please Notice it -
Deep Understanding about this example -

    If you are making object of this class and assign this object into variable.
     TestA  testa = new  TestA();

    In this case, reference testa will be stored in Stack Memory Allocation area but object (new  TestA()) will stored in Heap Memory Allocation area.
    In multi-threading concept, every thread has its own Stack Memory area but share same Heap memory area.
    Stack is thread safe but heap is not thread safe.

Comments

Recent Post

Recent Posts Widget

Popular posts from this blog

Capture image from webcam java code, examples

How to capture finger prints in java

Shallow Copy Deep Copy Java example