Very first lets look at what is stack and heap and finally we can explain how Java JVM allocate memory in those two areas.
Stack stores temporary variables created by a function/block. In stack, variables are declared, stored and initialized during runtime. This is not a long term or permanent memory and when function exist memory will be deleted. Specially stack is responsible to manager local variables, reference variables and methods. This is physical RAM and StackOverFlowError error comes when memory is not enough in java JVM. This has LIFO machisam.
Heap is to store global variables. All global variables are stored in heap memory space. It supports Dynamic memory allocation. In Java heap is created wheneven JVM is initializing . And heap will be up and running until the program exists. And memory should be managed by programmer. Unless garbase collector will clear unusing objects from memory. Unlike stack , heap allocate memory dynamically , not in order. All elements of heap memory can be accessed from any threads , so it is public.
There are few memory areas inside heap memory.
Yound generation space is the place for fresh objects in heap. This space be devide in to two parts such as :-
01. Eden Space
When a new object create from new keyword that object will be saved in this area.
02. Survivor Space
Any object survied from eden space belongs to here. This is also has two sections such as S0 and S1
Code cache area is containing memory which will be used for compilation and storage of native code