The main storage variables in the stack memory. When the lifecycle of a variable is reached, the variable is automatically released. Java heap memory mainly stores arrays and objects, and the lifecycle will become garbage, waiting for the garbage collection mechanism to recycle. Variables of some basic types defined in the function and referenced variables of the object are allocated in the function stack memory. WhenCodeWhen a block defines a variable, Java allocates memory space for the variable in the stack. When the scope of the variable is exceeded, Java Automatically releases the memory space allocated for the variable, the memory space can be used by another user immediately.
Heap memory is used to store objects and arrays created by new. The memory allocated in the heap is managed by the Java Virtual Machine's automatic garbage collector. After an array or object is generated in the heap, you can define a special variable in the stack so that the value of this variable in the stack is equal to the first address of the array or object in the heap memory, the variable in the stack becomes the referenced variable of the array or object. The referenced variable is equivalent to an array or object name.ProgramTo access the array or object in the heap.