Home >Java >Javagetting Started >What is the difference between stack and heap in java
Java Stack
The Java stack is always associated with a thread. Whenever a thread is created, the JVM will create a A corresponding Java stack will contain multiple stacks in this Java stack. These stack frames are associated with each method. Each time a method is run, a stack frame will be created that will contain some "internal variables" (in the method variables defined within), "operation stack" and "method return value" and other information.
Java Heap
The heap is where Java objects are stored. It is the core storage area for JVM to manage Java objects. The heap is what Java programmers should be most concerned about, because It is the storage area most closely related to our application and memory.
Every Java object stored in the heap will be a copy of the object's class. It will copy all non-static properties including inherited from its parent class.
The heap is shared by all Java threads, so access to it requires attention to synchronization issues, and methods and corresponding attributes need to ensure consistency.
Memory can be divided into 3 areas: method area (also called static area method), stack and heap
1. Method area
Stores all classes (that is, functions in classes are also stored in this area) and static variables. The method area stores the only elements in the entire program, such as classes and static variables. Can be shared by all threads, just like the heap.
2. Stack memory:
All local variables are stored, and once the scope to which the variable belongs ends, the variable is automatically released.
3. Heap memory
stores entities, arrays and objects (arrays are objects), and each entity has a first address value. Everything new comes out is in the heap memory and will be initialized by default. No manual release or automatic garbage collection is required.
Recommended tutorial: Java tutorial
The above is the detailed content of What is the difference between stack and heap in java. For more information, please follow other related articles on the PHP Chinese website!