Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer’s RAM .
Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it’s allocation is dealt with when the program is compiled. The stack is always reserved in a LIFO(Last in first out) order, the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack, freeing a block from the stack is nothing more than adjusting one pointer. You can use the stack if you know exactly how much data you need to allocate before compile time and it is not too big. The stack is attached to a thread, so when the thread exits the stack is reclaimed.
When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called.
Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory . Element of the heap have no dependencies with each other and can always be accessed randomly at any time. You can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time.The heap is typically allocated at application startup by the runtime, and is reclaimed when the application (technically process) exits. Heap can be Responsible for memory leaks.
obj1 = new Student();
In a multi-threaded situation each thread will have its own completely independent stack but they will share the heap.