Java and Memory
From a programming point of view, there are essentially six different places to store data on your computer. The fastest storage is the registers since this memory resides inside the processor itself. No high-level language gives you direct access to this memory.
The second fastest physical memory on your computer is the RAM. The RAM memory is logically divided into several categories by the compiler. When we use the stack, we are using the RAM. Stack has direct support from the processor via a stack pointer. Java object references are placed on the stack. The objects themselves remain on the heap.
Heap is a general purpose pool of memory where all Java objects live. It also resides in the RAM. Unlike the stack, the heap doesn’t require the compiler to know the amount of storage it would needs to be allocated in advance. Heap is more flexible than a stack but is also much slower.
Another logical division of the RAM is the static data. Static data members and references to static objects are placed here. Static objects themselves are placed on the heap. Constant data (marked by final keyword) are stored in the program code.
A tricky problem is streamed and persistent objects. Both are data that live outside the program and they must be able to exist even if the program is terminated. Such data is often placed on ROM memory.
Java Primitives Java primitive types are not references. The variable holds the value and is therefore stored in the stack. This is why operations involving primitives are faster than operations involving non-primitive objects. Wrapper classes of primitive data types are placed on the heap since they are Java objects.
Java primitive types have fixed sizes. An “int” is always 32 bits long; a “short” is always 16 bits long, and so on. All numeric types are signed. There are no unsigned primitive types. So primitive types are not only faster but also consume less memory.
Unlike many other programming languages, Java does not require you to manage your memory. All allocated memory which is no longer held by a code is automatically released by the garbage collector.