wisconsin
Memory

Memory

Curated by Last modified: 2 min read

Stack

The stack is a memory region which stores local variables, method calls, and references to objects. The stack is a LIFO (Last In First Out) data structure, meaning that the last element added to the stack is the first one to be removed.

Heap

The heap is a memory region which stores objects and arrays. The heap is a dynamic memory region, meaning that memory is allocated and deallocated as needed. The heap is shared among all threads in a Java program.

Static Memory

Static memory is a memory region which stores static variables and methods. Static memory is shared among all instances of a class and is loaded when the class is loaded by the JVM.

graph TD
%% Main Memory Container
    subgraph T[Total Program Memory]
        direction TB

    %% Stack Memory
        subgraph A[Stack]
            LocalVars[Local Variables]
            MethodCalls[Method Calls]
            ObjRefs[References to Objects]
        end

    %% Heap Memory
        subgraph E[Heap]
            Objects[Objects]
            Arrays[Arrays]
        end

    %% Static Memory
        subgraph H[Static Memory]
            StaticVars[Static Variables]
            StaticMethods[Static Methods]
        end
    end

Shallow Copy vs. Deep Copy

A shallow copy of an object is a copy of the object that shares the same references to the objects contained within the original object.

A deep copy of an object is a copy of the object that creates new references to the objects contained within the original object.

// Shallow Copy
int[] original = {1, 2, 3};
int[] copy = original;
// Deep Copy
int[] original = {1, 2, 3};
int[] copy = Arrays.copyOf(original);
graph TD
    %% Shallow Copy (Left Side)
    subgraph Shallow_Copy[Shallow Copy]
        direction LR
        Original1[original] --> Array1[Array]
        Copy1[copy] ---|Shares reference| Array1
    end

    %% Deep Copy (Right Side)
    subgraph Deep_Copy[Deep Copy]
        direction LR
        Original2[original] --> Array2[Array]
        Copy2[copy] -->|New reference| Array3[Array Copy]
    end

Garbage Collection

Garbage collection is the process of automatically freeing memory that is no longer in use by the program. The garbage collector runs in the background and identifies objects that are no longer reachable by the program (i.e. the amount of references to an objects reaches zero). These objects are then removed from memory, freeing up space for new objects.

Source

The existing course note was retained and normalized during the merge.

Related: Topic index.

Linked to this page