Java Interview Questions - Memory

Here are the most popular Java interview questions about memory.

See all questions

Explain the difference between Heap and Stack in Java.


The Heap Memory in Java is the space used by the JVM Runtime to allocate memory and store objects used throughout the program. Heap objects are shared across the entire program. The Heap has a special space called PermGen which is used for holding metadata about user classes and some other advanced functions.

The Stack Memory is used by the JVM fo

...

What parts of each line of the following code will be stored in the Heap and what parts will be stored in the Stack?


Before the main method is called, the program allocates Heap space and puts all the runtime classes and class-level objects into the Heap.

Line 1 - Creates stack space for the main method. The String arguments are in the Heap in the PermGen area, while references to the strings are stored in the Stack.

Line 2 - Puts the primitive x on the Sta

...

What is the significance of the Garbage Collector in Java? How does it work?


The Garbage Collector is an automatic memory management tool that reclaims memory by removing unused heap objects.

...

What are the automated memory management features of Java?


In comparison to other languages, the Java Runtime has several automated memory management features to improve the safety, reliability, efficiency, and ease of programming.

...

Describe a potential way of creating a memory leak in Java. Give an example.


Because Java has automated memory management, it precludes code errors relating to allocation of memory for objects and reclaiming memory from objects. This prevents user errors arising due to incorrect code for memory management, but it does not avoid design flaws that can result in memory leaks.

Example of Design flaw:

We are required to implem

...

Looking for developers?

Want to learn more about Gigster? Enter your email and we'll be in touch.