Witscale Test Center

1.5 Object creation with constructors > 1.5.2 Object creation behind the scene


1.5.2 Object creation behind the scene

We learned the syntax of the code for creating a Java object. It is equally interesting to learn what actually happens when you execute such code.

Java environment has a programming memory on which it creates all the objects. When a new object is created, some memory is automatically allocated to it. You (as a programmer) need not bother about the memory allocation issues while creating objects. This is because Java dynamically allocates and frees the memory and this operation is totally transparent to the programmer.

The programming memory is divided into two primary areas:

1.       Heap: Whenever an object is created with new, it is created on the memory heap. The heap area is a table of memory units. When the new statement creates a new object, free memory units from this table are allocated for the newly created object. When the object is no more in use and is no more referred by any references, it is not immediately destroyed. It becomes eligible for garbage collection[‡]. Eventually the memory is freed and the object is destroyed. 

2.       Stack: Stack is also a memory area. When you create object-reference variables and the local variables, they are stored on the stack. They remain on stack as long as they do not go out-of-scope. For instance, the local variables are destroyed as soon as the declaring method or block is exited. Similaraly, object-reference variables are destroyed as soon as they go out-of-scope.

Let us consider the following code to learn more about memory allocation. The code declares some primitives and creates few objects.

 

int a = 5;

String message = new String("Hello");

Date today = new Date();

char alphabet = ‘c';

 

 

 Figure 1.6 shows the memory model after the above code is executed. The primitives a and alphabet are stored directly on stack with values. The String object and the Date object are created on the heap and the reference variables for these objects are stored on stack.


Figure 1.6 Memory model after the Java code is executed

 

You need not know about memory model. However, understanding java’s memory model helps in understanding java’s object creation process well. This basic knowledge is especially useful while learning the other important concepts such as garbage collection, arrays, immutability of string objects.