Stack Memory:
Some basic types of variables and object reference variables defined in the function are allocated in the stack memory of the function. When a variable is defined in a block of code, Java allocates a memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically frees the memory space allocated for that variable, which can be used immediately by another.
Heap Memory:
Heap memory is used to hold objects and arrays created by new. The memory allocated in the heap is managed by the Java Virtual Machine automatic garbage collector. After creating an array or an object in the heap, you can also define a special variable in the stack that is equal to the array or the first address of the object in the heap memory, and this particular variable in the stack becomes the reference variable of the array or object. You can then use the reference variable in the stack memory in your program to access the array or object in the heap, which is the equivalent of an alias, or codename, of an array or object.
A reference variable is a normal variable that is defined when memory is allocated in the stack, and the reference variable is released in the program run to the extraterritorial scope. The array and the objects themselves are allocated in the heap, and even if the program runs outside the block of code that uses new to produce arrays and objects, the heap memory occupied by the array and the object itself will not be freed,
Comments:
Heap and Stack (Java memory)