WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Core Java · Advanced · question 44 of 100

What is the difference between a stack and a heap memory in Java?

📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

In Java, memory is divided into two main areas: the stack and the heap. The stack is used to store primitive types (such as int, boolean, etc.) and object references, while the heap is used to store objects and arrays.

Here are some key differences between the stack and the heap in Java:

Allocation: Memory on the stack is allocated in a contiguous block when a method is called, and is automatically freed when the method returns. Memory on the heap, on the other hand, is allocated dynamically at runtime and is not automatically freed.

Access: Access to memory on the stack is faster than access to memory on the heap, because the stack is a simple last-in, first-out data structure. Access to memory on the heap, however, is more complex because the heap is a more dynamic data structure.

Size: The size of memory on the stack is fixed at compile time, and is usually limited to a few megabytes. The size of memory on the heap, on the other hand, is dynamic and can grow or shrink as needed.

Here is an example of how the stack and heap are used in Java:

public class StackAndHeapExample {
    public static void main(String[] args) {
        int a = 5; // variable 'a' is stored on the stack
        String s = "hello"; // variable 's' is stored on the stack, 
        //but the string object is stored on the heap
        Object obj = new Object(); // variable 'obj' is stored on the stack, 
        //and the object is stored  on the heap
        int[] arr = new int[5]; // variable 'arr' is stored on the stack, 
        //and the array is stored on the    heap
    }
}

In this example, the primitive variable a and the string variable s are both stored on the stack, while the object reference obj and the integer array arr are stored on the stack but point to objects stored on the heap.

In summary, the stack and heap are both important memory areas in Java, and have different characteristics that make them suitable for different types of data. Understanding how these two memory areas work can help developers write more efficient and effective Java code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Core Java interview — then scores it.
📞 Practice Core Java — free 15 min
📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

All 100 Core Java questions · All topics