[Logo]
Forums Register Login
Memory allocation in Java
Hi all,
I am new to Java Tech., can anybody explain me how stack and heap works in Java for memory allocation.

Thanx in advance
Hi Pravin,

The heap stores all java objects whereas the stack holds local variables.

Best regards,
Simply put...
  • Primitive types (short, char, byte, int, long, float, double) are allocated in the Stack.
  • Object are allocated in the heap, while their references are allocated in the Stack.
  • Objects in the heap are subject to Garbage Collection while primitives in the Stack are not.


  • For more general info how Stack and Heap memory work see this.
    [ January 27, 2005: Message edited by: Vicken Karaoghlanian ]
     

    Originally posted by Vicken Karaoghlanian:
    Simply put...

  • [list] Primitive types (short, char, byte, int, long, float, double) are allocated in the Stack.
  • Object are allocated in the heap, while their references are allocated in the Stack.
  • [ January 27, 2005: Message edited by: Vicken Karaoghlanian ]


  • This is not entirely true. If the primitive types or object references are LOCAL variables, then they ARE allocated on the stack. However, if they are instance or class variables instead, they are allocated in the heap. (Of course, this was mentioned above, but I just wanted to reiterate.)

    Layne
    This is my favorite show. And this is my favorite tiny ad:
    Become a Java guru with IntelliJ IDEA
    https://www.jetbrains.com/idea/


    This thread has been viewed 688 times.

    All times above are in ranch (not your local) time.
    The current ranch time is
    Mar 25, 2019 12:16:10.