Java - Memory Management - Interview Questions and Answers on Heap

Q1.  What is a String Pool ?

Ans. String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

Q2.  Which are the different segments of memory ?

Ans. 1. Stack Segment - contains local variables and Reference variables(variables that hold the address of an object in the heap)

2. Heap Segment - contains all created objects in runtime, objects only plus their object attributes (instance variables)

3. Code Segment -  The segment where the actual compiled Java bytecodes resides when loaded

Q3.  Describe what happens when an object is created in Java ?

Ans. 1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data.

2. The instance variables of the objects are initialized to their default values.

3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its superclasses. This process continues until the constructor for java.lang.Object is called,
as java.lang.Object is the base class for all objects in java.

4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

Q4.  Different types of memory used by JVM ?

Ans. Class , Heap , Stack , Register , Native Method Stack.

Q5.  Which kind of memory is used for storing object member variables and function local variables ?

Ans. Local variables are stored in stack whereas object variables are stored in heap.

Q6.  Why do member variables have default values whereas local variables don't have any default value ?

Ans. member variable are loaded into heap, so they are initialized with default values when an instance of a class is created. In case of local variables, they are stored in stack until they are being used.

Q7.  Which memory areas does instance and static variables use ?

Ans. instance variables are stored on stack whereas static variables are stored on heap

Q8.  Why Java provides default constructor ?

Ans. At the beginning of an object's life, the Java virtual machine (JVM) allocates memory on the heap to accommodate the object's instance variables. When that memory is first allocated, however, the data it contains is unpredictable. If the memory were used as is, the behavior of the object would also be unpredictable. To guard against such a scenario, Java makes certain that memory is initialized, at least to predictable default values before it is used by any code.