0% found this document useful (0 votes)
2 views2 pages

Stack Vs Heap Java

The document explains the differences between Stack and Heap memory in Java. Stack memory is used for method calls and local variables, is fast, and is thread-specific, while Heap memory is for objects created with 'new', is slower, and shared among all threads. A summary table highlights key features such as scope, speed, garbage collection, and thread safety.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Stack Vs Heap Java

The document explains the differences between Stack and Heap memory in Java. Stack memory is used for method calls and local variables, is fast, and is thread-specific, while Heap memory is for objects created with 'new', is slower, and shared among all threads. A summary table highlights key features such as scope, speed, garbage collection, and thread safety.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Stack vs Heap in Java

1. Stack Memory

- Used for storing method calls and local variables.

- Follows LIFO (Last-In-First-Out).

- Each thread has its own stack.

- Very fast memory allocation and deallocation.

- Automatically cleared when method finishes.

Example:

int a = 5; // 'a' stored in stack

Method calls push a new stack frame, removed on return.

2. Heap Memory

- Used for storing objects created with 'new'.

- Shared among all threads.

- Slower access compared to stack.

- Managed by Garbage Collector.

- Used for large and long-lived data.

Example:

Person p = new Person(); // Object in heap, 'p' in stack

3. Summary Table

Feature | Stack | Heap

------------------|-----------------------|-----------------------------

Scope | Method local | Global to app (shared)


Stack vs Heap in Java

Speed | Fast | Slower

Garbage Collected | No | Yes

Thread Safety | Yes | No (needs sync)

Stores | Primitives, refs | Objects, arrays

4. Real-world Analogy

- Stack is like your kitchen counter: temporary workspace, cleared often.

- Heap is like your fridge/pantry: long-term storage, shared by everyone.

Example: Car car = new Car();

- 'car' reference is on the stack

- Car object itself is on the heap

You might also like