You can look at this explanation.
Java divides memory into two types: one is stack memory and the other is heap memory. Some basic types of variables defined in the function and reference variables of objects are allocated in the stack memory of the function. When defining variables in a code block,
Heap memory is used to store objects and arrays created by new, and the allocated memory in the heap is managed by the automatic garbage collector of java virtual machine. After generating an array or object in the heap, you can also 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, and this variable in the stack becomes a reference variable of the array or object. Later, you can use the reference variable in the stack to access the array or object in the heap. The reference variable is equivalent to the name of the array or object. Reference variables are ordinary variables, which are allocated in the stack when defined, and released after the program runs out of its scope. Arrays and objects themselves are allocated in the heap. Even if the program runs outside the code block where the statement using new to generate arrays or objects is located, the memory occupied by arrays and objects themselves will not be released. When no reference variables point to arrays and objects, they become garbage and can no longer be used, but they still occupy memory space and are taken away (released) by the garbage collector at an uncertain time. This is also the reason why java occupies more memory.
Java allocates memory space for this variable in the stack. When it exceeds the scope of the variable, Java will automatically release the memory space allocated for this variable, which can be used for other purposes immediately.