Friday, January 8, 2010

How Java Objects use Heap Memory

In this blog, lets look at how objects are stored in memory in Java so that you can understand at a lower level what happens when you create and manipulate the objects that make up your programs

A typical Java program contains many Java language attributes like Classes, Methods, Variable, Objects etcThrough these object interactions, a program can carry out various tasks, such as implementing a GUI,running an animation, or sending and receiving information over a network

There are two kinds of memory used in Java.
Stack memory
Heap memory.

Stack memory stores primitive data types.

Heap memory stores the java objects (When a new object is invoked in java program). See below for how object is created in java program

When you are done with an object, the memory is reclaimed for you automatically via Garbage collection runs as a thread in the background, looking for objects that no longer have a usable reference. When it finds them, it destroys them and reclaims the memory.

An object reference on the stack is only an address that refers to the place in heap memory where that object is kept.

As Java programmer, you do not have to directly address memory allocation
and recovery of memory space.

Below is snapshot of code which creates three objects:
One Point object and two Rectangle objects.

Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

Primitive data types have just one value to store. For instance:
int i = 1;

The appropriate amount of space is allocated given the data type, and the variable is stored in memory just as it is.