0% found this document useful (0 votes)
2 views

Java Basics

In Java, objects are created using the 'new' keyword, which allocates memory for them on the heap. The object's constructor initializes its state, and references to the object are stored in reference variables, allowing access and manipulation. The Java Garbage Collector automatically manages memory, reclaiming space for objects that are no longer referenced, while the stack is used for method execution and local variable storage.

Uploaded by

ASK 011
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Basics

In Java, objects are created using the 'new' keyword, which allocates memory for them on the heap. The object's constructor initializes its state, and references to the object are stored in reference variables, allowing access and manipulation. The Java Garbage Collector automatically manages memory, reclaiming space for objects that are no longer referenced, while the stack is used for method execution and local variable storage.

Uploaded by

ASK 011
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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.

You might also like