(a): Distinguish between heap and Stack in Java memory:1. Stack: Data can be shared, hold the basic data type and object reference, where the object is stored in the heap, the object's reference is stored in the stack; When a variable is defined in a block of code, the variable is allocated memory space in the stack, and when the variable exits the scope, Java automatically frees up the allocated memory space for the variable, and the memory space can be used for other purposes immediately. 2. Heap: Store data generated with new, in which the garbage collection mechanism is used for garbage disposal. After generating 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. Arrays and objects become garbage when no reference variable points to it, cannot be used, but still occupy memory space, and are collected (released) by the garbage collector at a later indeterminate time. 3. Related code:
Packagezdbstring; Public classTest {/** This source file is primarily a test of the memory of string in Java The difference between the principle, the operator "= =" and the Equals () of the function * Summary: (1) The reference str1 is placed on the stack, the string constant hello is placed in the constant pool, the reference str1 points to the hello in the constant pool; The reference str3 is stored in the stack while a new memory is opened in the heap to hold the string object. (2) * Related link URL:http://jingyan.baidu.com/article/8275fc869a070346a03cf6f4.html */ Public Static voidMain (string[] args) {String str1= "Hello"; String str2= "Hello"; String STR3=NewString ("Hello"); String STR4=NewString ("Hello"); System.out.println ("str1==str2===" + (STR1==STR2));//trueSystem.out.println ("str1.equals (str2) = = = =" + (Str1.equals (str2)));//trueSystem.out.println ("str3==str4===" + (STR3==STR4));//falseSystem.out.println ("str3.equals (STR4) = = = =" + (Str3.equals (STR4)));//trueSystem.out.println ("str1==str3===" + (STR1==STR3));//falseSystem.out.println ("str1.equals (str3) = = = =" + (Str1.equals (STR3)));//true } } View Code
4. Related Memory diagram:
Related knowledge points for string memory in Java