"Space for objects created with the new operator are allocated in the heap. Method arguments or local variables of primitive types are created on the stack. Objects created in the heap have a longer lifetime. Objects are kept on the heap, and since objects can contain instance variables of primitive types, these primitive variables are kept on the heap as well."
Can anyone throw more light on the above? I seem to have mixed up my understanding in the above statements.
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.
Objects must be stored differently because they are more complex. They often hold multiple values, each of which must be stored in memory. The association between each value and the object must be maintained throughout its life. An object reference variable must then hold a reference to those values. This reference represents the location where the object and its metadata are stored.
There are two kinds of memory used in Java. These are called stack memory and heap memory. Stack memory stores primitive types and the addresses of objects. The object values are stored in heap memory. An object reference on the stack is only an address that refers to the place in heap memory where that object is kept.
Say you've got two Test objects, and you assign the first to the second, like this:
Test test1 = new Test(); Test test2 = new Test();
test2 = test1;
What you're actually doing when you write this is assigning the address of the test1 object to the test2 object. Assume that test1's memory address was 0x33d444 and that test2's address was 0x99f775. After performing the above assignment, test2 now holds this address in stack memory: 0x99f775, which refers to the same object as test1. The test2 object on the heap still exists, but it cannot be accessed. That's because this reassignment overwrote the old address that test2 was keeping on the stack. This kind of reassignment makes two stack references to the same object on the heap.
It is useful to know that these two different kinds of memory exist in Java. Stack memory is the program's memory, and heap memory resides outside of the program.
As a Java programmer, you do not have to directly address memory allocation and recovery of memory space, which is a common headache for C++ programmers. When you need a new object, Java allocates the required memory. When you are done with an object, the memory is reclaimed for you automatically via Java's garbage collection facility.