← Back to Home

Module 4: Memory

Module Overview

In this module, you'll learn about memory management in Java applications. You'll understand how the JVM handles memory, learn about different memory areas, and explore techniques for optimizing memory usage.

Learning Objectives

Key Topics

Introduction to Memory

Learn about the JVM memory architecture and how memory is managed in Java applications.

JVM Memory Architecture

The Java Virtual Machine (JVM) manages memory in several different areas:

  • Stack: Stores method frames, local variables, and partial results
  • Heap: Stores all objects and their instance variables
  • Method Area: Stores class structures, static variables, and method code

Stack vs. Heap

Understanding the difference between stack and heap memory is crucial:

  • The stack is organized as frames, with each frame representing a method call
  • Each stack frame contains local variables and references to objects in the heap
  • The heap stores all objects, regardless of where they were created
  • References to heap objects can be stored in local variables (on the stack) or as fields in other objects (on the heap)

Example: Memory Allocation

public class MemoryExample {
    public static void main(String[] args) {
        // Local primitive variable - stored on stack
        int count = 5;
        
        // Object reference stored on stack, object stored on heap
        Person person = new Person("Alice", 30);
        
        // Method call creates new stack frame
        doSomething(person);
    }
    
    public static void doSomething(Person p) {
        // Local primitive - stored on stack in the doSomething frame
        int age = p.getAge();
        
        // New object created on heap, reference on stack
        String message = "Hello, " + p.getName();
        
        System.out.println(message);
        
        // When method exits, stack frame is removed
        // If no more references to message exist, it becomes eligible for garbage collection
    }
}

class Person {
    // Instance variables stored on heap with the object
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() { return name; }
    public int getAge() { return age; }
}
Read More

Memory Storage

Explore different memory areas and how they are used in Java applications.

Read More

Garbage Collection

Understand garbage collection algorithms and how to optimize them.

Read More

Memory Optimization

Learn techniques for optimizing memory usage and preventing memory leaks.

Read More

Resources

Code Resources