How are Java Objects Stored in Memory?

Class is a user-defined data type which is naturally used to declare objects of that type. So, an object is a real-world entity, having a set of attributes and behavior. However, an object can’t be simply declared as same as primitive types.

How are Java Objects Stored in Memory?

In Java, creation of an object is a two-step procedure where we first declare an object of that class type and then a physical copy of the actual object of the class is assigned to that variable.

java memory object

This assignment of an actual copy of the object is done by using ‘new keyword’ for dynamic allocation of memory. A ‘new keyword’ allocates memory in heap and a reference to the allocated object which is nothing but an address is stored in the variable of the respective reference type.

Syntax:

Myclass obj;   //  Not an object, just a reference variable 

Obj = new Myclass(); // instantiation and initialization object
  •  A reference variable is created and used to store the address of an object.
  • A ‘new keyword’ paired with a constructor is used to assign the reference variable, this is how instantiation and initialization of an object take place. Instantiation of an object is done by new, whereas Initialization is by the constructor of that class. A constructor initializes the newly created objects.

Each time when an object is declared, it is said to be an instance of a class is created.

How java Objects are stored in memory

An object gets memory on the heap. In stack memory, the variable of class type stores the address of an object.

In heap memory, a physical copy of an object is stored and the reference or address of this copy in the variable of the associated class. Objects that can no longer be referenced are cleaned up by Garbage collector.

Java program to demonstrate the working of object

class myclass{
void display(){

System.out.println("I am printing");
}

}
public class Sample1 {

public static void main(String[] args) {
myclass obj;
obj= new myclass();
obj.display();
}

}

 

Output:

I am printing

Leave a Reply