Saturday, September 20, 2014

IMP Questions and answer in Heap and Stack Memory area in Java

Question - Stack Vs Heap Memory

Answer - Main difference between heap and stack is that stack memory is used to store local variables and function call, while heap memory is used to store objects in Java. No matter, where object is created in code e.g. as member variable, local variable or class variable, they are always created inside heap space in Java.

In a multi-threaded application, each thread will have its own stack, but, all the different threads will share the heap. Because the different threads share the heap in a multi-threaded application, this also means that there has to be some coordination between the threads so that they don’t try to access and manipulate the same piece(s) of memory in the heap at the same time.

Question - Can an object be stored on the stack instead of the heap?

Answer -  Yes, an object can be stored on the stack. If you create an object inside a function without 
using the “new” operator then this will create and store the object on the stack, and not on the heap. 

No comments:

Post a Comment