Java Object Memory Allocation
Chapter:
Miscellaneous
Last Updated:
21-10-2016 13:07:43 UTC
Program:
/* ............... START ............... */
class Test {
// class contents
void show() {
System.out.println("Test::show() called");
}
}
public class JavaObjectMemoryAllocation {
public static void main(String[] args) {
Test t = new Test(); // all objects are dynamically allocated
t.show(); // No error
}
}
/* ............... END ............... */
Notes:
-
In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In C++, when we allocate abject using new(), the abject is allocated on Heap, otherwise on Stack if not global or static.
- In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new().
Tags
Memory Allocation, Java, Miscellaneous