Java divides memory into two types: one is stack memory and the other is heap memory. Some of the basic types of variables and object reference variables defined in a function are allocated in the stack memory of the function. When a variable is defined in a block of code, Java allocates memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically releases the memory space allocated for the variable. The memory space can be used as an immediate alternative.
Heap memory is used to hold objects and arrays created by new, and the memory allocated in the heap is managed by the automatic garbage collector of the Java virtual machine. After an array or object has been generated in the heap, you can also define a special variable in the stack so that the value of the variable in the stack equals the first address of the array or object in the heap memory, the variable in the stack becomes the reference variable of the array or object, and then you can In order to access an array or object in the heap using a reference variable in the stack, a reference variable is equivalent to a name that is an array or an object. A reference variable is a normal variable that is assigned in the stack when defined, and the reference variable is released after the program runs beyond its scope. and the arrays and the objects themselves are allocated in the heap, even if the program runs to a block of code that uses new to produce an array or an object's statements, the memory occupied by the array and the object itself is not freed, and the array and object become garbage when they point to it without a reference variable, and cannot be used, but still occupy the memory space. Be taken Away (released) by the garbage collector at a later uncertain time.
This is the Java comparison for memory, in fact, the variables in the stack point to the variables in the heap memory, this is the pointer in Java!