---
# System prepended metadata

title: JAVA memory- STACK vs HEAP
tags: [JAVA, memory]

---

# JAVA memory- STACK vs HEAP

###### tags: `JAVA`,`memory`

ref: 
[JAVA String pool](/VwrnsFUORAytbFnCyhX6dw)
[introduce video](https://www.youtube.com/watch?v=UcPuWY0wn3w&ab_channel=ImtiazAhmad)
[pic ref](https://www.baeldung.com/java-stack-heap)


|                    |                                       stack                                        |                                                   heap                                                    |
|:------------------:|:----------------------------------------------------------------------------------:|:---------------------------------------------------------------------------------------------------------:|
|    Application     |         Stack is used in parts, one at a time during execution of a thread         |                           The entire application uses Heap space during runtime                           |
|        Size        |     Stack has size limits depending upon OS, and is usually smaller than Heap      |                                      There is no size limit on Heap                                       |
|      Storage       | 1. primitive variables and 2. references to objects that are created in Heap Space |                                           newly created objects                                           |
|       Order        |                                        LIFO                                        | include Young Generation, Old or Tenured Generation, and Permanent Generation.(perm removed after JAVA 7) |
|        Life        |         Stack memory only exists as long as the current method is running          |               Heap space exists as long as the application runs OR before the GC collection               |
|  call Efficiency   |                                       faster                                       |                                                  slower                                                   |
| allocate/delocated |    automatically allocated and deallocated when a method is called and returned    |    when new objects are created and deallocated by Gargabe Collector when they're no longer referenced    |


![](https://i.imgur.com/bT8N8pQ.png)

```java=
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);
    }
}
```


