Difference between heap and stack in java
Both heap and stack are places where Java is used to store data in RAM.
Heap
(1)The Java heap is a runtime data zone, and class objects are allocated space from the heap.. These objects are created using commands such as new and destroyed by the garbage collector.
(2) The advantage of heap is that the memory space can be dynamically allocated. You do not have to tell the compiler about the memory space required because it is dynamically allocated at runtime. However, because the memory needs to be dynamically allocated at runtime, the access speed is slow.
Stack
(1)The stack mainly stores some basic data type variables (Byte,Short,Int, long, float, double, boolean, char) and object references.
(2) The advantage of stack is that the access speed is faster than that of stack, and stack data can be shared. However, the disadvantage is that the amount of memory space occupied by data stored in the stack needs to be determined during compilation, which lacks flexibility.
Example: stack data can be shared
String can be created in either of the following ways:
String str1 = new String("abc");String str2 = "abc";
First, use new to create an object, which is stored in the heap. Each call creates a new object.
The second is to first create the reference str2 of the object in the stack, and then find whether "abc" is stored in the stack. If not, store "abc" into the stack, and direct str2 to "abc". If "abc" already exists, direct str2 to "abc ".
The following code illustrates the above theory:
public static void main(String[] args) { String str1 = new String("abc"); String str2 = new String("abc"); System.out.println(str1 == str2); }
The output result is: false.
public static void main(String[] args) { String str1 = "abc"; String str2 = "abc"; System.out.println(str1 == str2); }
Output result: true
Therefore, the second method is used to create multiple "abc" strings, and only one object exists in the memory. This method can save memory space. At the same time, the program running speed can be improved because the JVM automatically determines whether to create new objects based on the actual data in the stack.
You are welcome to repost, but please keep the original source of the article
Address: http://www.cnblogs.com/nnngu/p/8300761.html