/** * Created by PhpStorm. * User: Rahul * Date: 12/8/2016 * Time: 8:09 PM */ Core Java..

Heap vs Stack memory area

Core Java

Difference between Stack vs Heap in Java

stack is also a data structure which is used to store elements in LIFO(Last In First out) order and available in Java API as java.util.Stack. Java uses both stack and heap memory for different needs.

differences between stack and heap memory in Java:-

Each Thread in Java has there own stack which can be specified using -Xss JVM parameter, similarly you can also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is starting size of heap and -Xmx is maximum size of java heap

Can the stack grow in size? Can the heap grow in size?

The stack is set to a fixed size, and can not grow past it’s fixed size (although some languages have extensions that do allow this - see the C standard library function alloca(), malloc()). So, if there is not enough room on the stack to handle the memory being assigned to it, a stack overflow occurs. This often happens when a lot of nested functions are being called, or if there is an infinite recursive call.

If the current size of the heap is too small to accommodate new memory, then more memory can be added to the heap by the operating system. This is one of the big differences between the heap and the stack.

How is memory deallocated on the stack and heap :-

Data on the stack is automatically deallocated when variables go out of scope. However, in languages like C and C++, data stored on the heap has to be deleted manually by the programmer using one of the built in keywords like free, delete, or delete[ ].

Other languages like Java and .NET use garbage collection to automatically delete memory from the heap, without the programmer having to do anything..

Click here to access OOp's Concept

feel free to ask any of your doubts