Both heap and stack are common storage structures in Java, where data is stored in memory.
Heap: A variable that primarily holds a reference type, and the object that the runtime creates (new). Mainly used for storing objects, the access speed is slow, can be run dynamically allocated memory, the life cycle does not need to determine in advance.
Stack: A variable that primarily holds the underlying type, and a reference variable for the object. Mainly used for executing programs, access speed, the life cycle must be determined in advance, lack of flexibility.
public class test{ public static void main (string[] args) { int i=0; // basic data type variable duck duck =new Duck (1,1000); // duck is the reference variable for the object, the stack exists, and the duck (1,1000) is the actual object that exists in the heap. }}
The memory allocation situation is as follows:
The difference between heap and Stack in Java