0% found this document useful (0 votes)
3 views7 pages

1. Java Memory Management

Java memory management involves automatic allocation and deallocation of memory by the JVM, utilizing garbage collection to reclaim unused objects. Memory is divided into stack and heap, where stack memory handles local variables and method calls, while heap memory stores objects and instance variables managed by the garbage collector. Stack overflow occurs due to excessive method calls, while heap overflow arises from continuous object allocation without sufficient garbage collection.

Uploaded by

gokuthecrackhead
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)
3 views7 pages

1. Java Memory Management

Java memory management involves automatic allocation and deallocation of memory by the JVM, utilizing garbage collection to reclaim unused objects. Memory is divided into stack and heap, where stack memory handles local variables and method calls, while heap memory stores objects and instance variables managed by the garbage collector. Stack overflow occurs due to excessive method calls, while heap overflow arises from continuous object allocation without sufficient garbage collection.

Uploaded by

gokuthecrackhead
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

Java Memory Management

Java memory management is the process by which the Java Virtual Machine (JVM) automatically handles the allocation and deallocation of memory. It
uses a garbage collection to reclaim memory by removing unused objects, eliminating the need for manual memory management.

Example:
Scanner sc = new Scanner([Link]);
// Here, the Scanner object is in the heap, // while the reference sc is in the stack.

Short recall:

 Hard disk (storage) is used for:


o saving files
o storing programs when not running Heap memory → Managed by the garbage collector (GC) (inside
 When you run a program: JVM).
it is loaded from disk → into RAM → then uses stack + heap Objects live here. When they are no longer reachable, GC frees
them.
 RAM (main memory) is where programs run while executing
Stack memory →It is managed automatically by the runtime
 Stack and Heap are just two regions inside RAM used by a running
(JVM), not GC
program
It stores method calls, local variables, and references.
When a method finishes, its stack frame is removed immediately.

Example: When test() ends:


void test() {
int x = 10; // stored in stack  x is removed from stack automatically
Person p = new Person(); // reference in stack, object in heap  p (reference) is removed from stack
}  The Person object remains in heap until GC removes it (if no
references exist).

Page 1 of 7
Java stack vs. heap memory allocation

In Java, memory allocation is primarily divided into two categories, i.e., Stack and Heap memory. Both are used for different purposes, and they have
different characteristics.
 Stack memory stores primitive local variables, method call information, and references to objects during program execution. Memory is
automatically allocated when a method starts and cleared when it ends. Data exists only during the method’s execution. If the stack runs out of
space, a StackOverflowError occurs.

 Heap Memory is used for objects and instance variables. The size depends on the class structure. The GC manages this area by removing unused
objects.
Example:

Page 2 of 7
Memory representation for the above example:

 emp1 and emp2: references stored on stack.


 new Employee(...): objects stored in heap.
 "Maddy"; stored once in String Pool (heap).
 Both [Link] and [Link]: point to the same string object.
 display(emp1): creates a stack frame, parameter emp points to emp1
then emp2.
 ([Link] == [Link]): true since both refer to the same pooled
string.

Page 3 of 7
Hi! I am the Garbage Collector (GC) working inside the JVM.

Heap

Garbage Collection in Java:

Garbage collection in Java is an automatic memory management process that helps Java programs run efficiently.
 Objects are created on the heap area.
 Eventually, some objects will no longer be needed.
 Garbage collection is an automatic process that removes unused objects from heap.

Working of Garbage Collection

 It identifies which objects are still in use (referenced) and which are not in use (unreferenced).
 It removes the objects that are unreachable (no longer referenced).
 The programmer does not need to mark objects to be deleted explicitly . Garbage collection is implemented within the JVM.

Page 4 of 7
References generally are stored in:

 Stack → if local
 Heap → if part of an object

Example: Student HAS-A Course

What is happening in memory:

 C1 → reference in stack, points to Course object in heap


 S1 → reference in stack, points to Student object in heap
 Inside the Student object:
o studentName → stored in heap
o course → reference stored in heap, pointing to the
Course object

Key point:

The course field inside Student is a heap-stored reference to


another heap object.

Page 5 of 7
 c1 (stack) → points to Course
Stack Heap
 [Link] (heap) → also points to the same Course

c1 Course object If you remove c1:


name: "OOP II"
c1 = null;

 Stack lost the reference (c1 = null)


s1 Student object
 BUT heap still holds it ([Link])
studentName: "Sherlock"
course: So, the Course object is NOT eligible for GC.
Only when all references (stack + heap) are gone will GC clean it.

Creating the Course inside Student is simpler, but in the above code, Student does not decide how a Course is created. It simply uses it. This is
called loose coupling, and it is considered a better design practice.

When does a stack overflow occur in a Java program? Can a heap overflow also occur in Java?

Stack overflow in Java

A stack overflow happens when the call stack grows beyond its limit. This usually occurs due to too many method calls without returning.

Example:
void recurse() { Each call adds a new stack frame. Since there is no stopping condition, the stack
recurse(); // no base case keeps growing until the JVM throws: [Link]
}

Possible causes

 Uncontrolled recursion (most common cause)


 Very deep but finite recursion
 Methods with large local variables (rare but possible)
 Too many nested method calls

Page 6 of 7
Key idea: stack overflow is about call depth, not object size.

Can heap overflow occur?

Yes. In Java, this is called: [Link]: Java heap space

It happens when the program keeps allocating objects and the GC cannot free enough memory.

Example:
import [Link];
public class Test {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();

while (true) {
[Link]("This is a long string to consume heap memory " + [Link]());
}
}
}

Here:
 Objects are continuously created
 References are kept in list
 GC cannot reclaim them → heap fills up → error

Simple comparison
Feature Stack Overflow Heap Overflow
Error type StackOverflowError OutOfMemoryError

Cause Too many method calls Too many objects

Memory area Stack Heap

Typical reason Infinite recursion Memory leak / large data

Page 7 of 7

You might also like