DEV Community

Prashant Mishra
Prashant Mishra

Posted on • Originally published at baeldung.com

Memory Management in Java

There are primarily two tyes of memories that store primitive variables, objects, referenes of the objects, call to the different methods.

- Stack memory in java

Whenever we call new method a new block is created on top of the stack that has primitive variables, references to the object related to that method.

When the method is finished with the execution the space is freed from the stack and is made available.

If this memory is full java throws StackOverflow Error
For example : This stackoverflow exception you must have seen when your recursive code does not have a proper base case.

- Heap memory in java

This is used for dynamic memory allocation for java objects and JRE classes at runtime.

New objects are always stored on heap memory (having global access i.e. accessible from anywhere in the program) and its reference is stored on stack memory.
If this memory is full java throws OutOfMemory Error.

This memory is not automatically freed it requires garbage collector to free up space by deallocating the memory allocated to already created objects.

For better understandig see the below code and its memory allocation process by JVM

class Person {
    int id;
    String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

public class PersonBuilder {
    private static Person buildPerson(int id, String name) {
        return new Person(id, name);
    }

    public static void main(String[] args) {
        int id = 23;
        String name = "John";
        Person person = null;
        person = buildPerson(id, name);
    }
}
Enter fullscreen mode Exit fullscreen mode

code and image source

Top comments (0)