I recently read several posts about the differences between Java heap and stack. I have some knowledge of these two concepts.
Understanding.
Java heap and stack are actually memory resources. Memory Resources are mentioned here. By the way
Java memory is not just a stack or heap. There are also registers and constant pools.
The Java heap memory is a runtime data area that can dynamically allocate the memory size to survive.
The cycle does not need to be implemented to tell the compiler to store objects and arrays. The advantage is that dynamic allocation is flexible and lacks
Point is slow access.
The java stack memory is a region where data can be shared. The data size and lifecycle in the stack are
OK. Some basic variables and object handles are usually stored in the stack. Lack of flexibility and fast access.
In fact, I feel that it is okay to sum up these two sentences to deal with some interview questions. For example
String str1 = new string ("fish"); new outputs an object, which is naturally heap.
String str2 = "fish" is a variable reference that will exist in the stack. So it is obvious that str1!
= Str2. If str3 = "fish ". He is also in the stack and data is shared in the stack, so str2 = str3.
String str4 = new string ("fish"); although both str4 and str1 create objects in
Heap. But I didn't say that the data in the heap is shared, so they only have the same value, but str1!
= Str4 in the string equals method I understand it as comparing whether the values are equal. So it's reasonable.
The three values are the same, so they are equal.
Speaking of str1! = Str4, I think of a problem because they are two independent objects with different
From the lifecycle. Therefore, their life cycle is uncertain. They are created by running the call and do not need to be deleted.
. So it will be automatically recycled by GC (Java Garbage Collector ). Therefore, the data in the heap can be processed by GC.
Automatic Recovery. If it cannot be recycled, memory overflow may occur. Generally, memory overflow may be short-lived.
Periodic variables are defined with a long life cycle, causing data to be not used in the memory, but occupy memory resources.
You can manually recycle it.
If it is a new object, it indicates that its life cycle is generated because of running and does not need to die. This is acceptable.
Improve memory efficiency and do not always occupy resources. So now we can know that string STR = new
String (""); better than string STR =.