Reference website: http://www.cnblogs.com/xwdreamer/archive/2012/04/01/2428857.html
Java divides memory into two types: one is stack memory and the other is heap memory. Some basic types of variables and object reference variables defined in the function are allocated in the stack memory of the function, and when a variable is defined in a block of code, Java allocates the memory space for the variable in the stack, when the scope of the variable is exceeded ( For example, when function B is called in function A, the variable A is defined in function B, the scope of variable A is only function B, and after function B is finished, variable A is automatically destroyed.) The memory allocated to it is reclaimed, and Java automatically frees up the allocated memory space for that variable, which can be used as an immediate alternative.
heap memory is used to store the 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 creating an array or an object in the heap, you can also define a special variable in the stack that is equal to the first address of the array or object in the heap memory, and this variable in the stack becomes the reference variable of the array or object. The reference variable in the stack can then be used in the program to access an array or an object in the heap, which is equivalent to a name that is an array or an object. A reference variable is a normal variable that is allocated in the stack when defined, and the reference variable is freed after the program runs outside its scope. While the array and the object itself are allocated in the heap, the memory occupied by the array and the object itself is not freed when the program runs beyond the block of code that uses new to produce the array or object's statement, and the array and object become garbage when no reference variable points to it, not in use, but still occupy memory space. The garbage collector takes off (releases) at a later indeterminate time. This is the reason why Java compares memory, in fact, the variables in the stack point to the variables in the heap memory, this is the pointer in Java!
Areas of memory commonly used in Java
There are mainly 4 memory spaces in Java, the names and functions of these memory are as follows:
- Stack memory space: Saves all object names (more precisely the address of the heap memory space where the reference is saved)
- Heap memory space: Saves the specific property content of each object.
- Global Data area: Saves properties of the static type.
- Global Code Area: Saves all the method definitions.
Java and memory