## Notes
- Heap memory
- Stack memory
- Method area
- Metaspace replaced Permanent Generation in Java 8
- Now grows in memory by default; Permanent Generation was the cause of [[OutOfMemoryError]]
- When Metaspace reaches capacity, automatically triggers [[garbage collection]]
- Program Counter Register
- Native Method Stack
## Heap Memory
- Heap memory is allocated as soon as the JVM starts
- It can be configured by the user through CLI flags
- Objects and arrays are stored here; references are stored in stack memory
## Method Area
- A logical part of the heap
- Stores class-level information
- Class structures
- Method bytecode
- Static variables
- Constant pool
- Interfaces
- Garbage collection is not guaranteed
## Stack Memory
- Each function/method has its own stack
- Main method has its own stack
- Origin of [[StackOverflowError]] when stack has run out of memory
## Object Creation
When an object is created
```java
class MyClass {
int myInstanceVariable = 5;
public int add(int n1, int n2) {
return n1 + n2;
}
}
```
1. Its reference variable is stored in the stack
2. The heap allocates memory to the object and sets the heap memory address in the stack
3. Its instance variable, `myInstanceVariable`, is stored in heap, in the allocated memory for the object
## Program Counter Register
- Each thread has its own PC Register
- Each thread executes the code of any single method at any given time
## Native Method Stack
- Similar to Java Method Stacks, each native method has its own stack in native memory
- Native means that it belongs to underlying C/C++ implementations