When we create an object the instance is stored in
heap ?
Ans: Yes
Java uses dynamic memory allocation on the heap to create and manage
objects.
1. Object Creation: new keyword to create an object, Java allocates
memory for that object on the heap.
2. Initialization: The constructor of the object is called to initialize its
state. You can define your own constructors for custom initialization.
3. Reference: You typically store a reference to the object in a reference
variable. This reference allows you to access and manipulate the
object.
4. Lifetime: The object remains in the heap memory until it is no longer
referenced or reachable from any part of your program. At that point,
the Java Garbage Collector (GC) may identify and reclaim the memory
occupied by unreachable objects.
Automatically -> Garbage Collector helps to simplify memory
management for developers and reduce the risk of memory leaks.
Developers don't have to explicitly(manually) deallocate memory
as they do in languages like C or C++.
The stack in Java is primarily used for managing the execution of
methods and storing local variables within method call frames.
Object instances are typically stored on the heap to allow for dynamic
and longer lifetimes, while the references to those objects are
managed on the stack or within other objects.
It's important to be aware of how references work in Java to understand
how objects are managed in memory. Java uses references to
access objects on the heap, and these references are stored in local
variables, fields, and other data structures. When there are no more
references to an object, it becomes eligible for garbage collection.