What is Stack and Heap Memory?

Heap Memory
Class instances and arrays are stored in heap memory. Heap memory is also called as shared memory. As this is the place where multiple threads will share the same data.

Non-heap Memory

It comprises of ‘Method Area’ and other memory required for internal processing. So here the major player is ‘Method Area’.

Stack Memory

The two sections other from the code segment in the memory are used for data. The stack is the section of memory that is allocated for automatic variables within functions.

Data is stored in stack using the Last In First Out (LIFO) method. This means that storage in the memory is allocated and deallocated at only one end of the memory called the top of the stack. Stack is a section of memory and its associated registers that is used for temporary storage of information in which the most recently stored item is the first to be retrieved.

When you create an object using the new operator, for example myobj = new Object();, it allocates memory for the myobj object on the heap. The stack memory space is used when you declare automatic variables.
Note, when you do a string initialization, for exampleString myString;, it is a reference to an object so it will be created using new and hence it will be placed on the heap.

Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email