0

I know that memory allocated for functions and static members is done only once, and that class variables are given new memory space each time a new object is created.

Once I use the new operator in this following problem, I will get 8 bytes for the class variables. But, when is memory for int c allocated? During compile time?

class A
{
    int a,b;

    void show()
    {
        int c;
    }

    public static void main(String...s)
    {
        new A().show();
    }
}
Raedwald
  • 46,613
  • 43
  • 151
  • 237
a dawg
  • 69
  • 8

2 Answers2

3

Method calls and local variables are stored on stack. Objects (containing instance variables) are stored on heap. So the object created using:

new A()

will be stored on heap and show method local variable c will be created stored on stack when you call the method.

Just check this image to understand more about stack and heap memory management in Java:

enter image description here

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • helpful... :D now pls expalin this- once first() is put onto stack , ( this happens during compile time right?). then memory is allocated to it.and if we again call first , then fresh memory will be allocated to first() or is this just a function call to a fixed memory location elsewhere? – a dawg Sep 14 '13 at 05:55
2

The memory for a function's local variables is allocated each time the function is called, on the stack.

ash
  • 4,867
  • 1
  • 23
  • 33
  • so each time new memory is allocated to local vars? i thought that memory was allocated only once to functions and their vars! – a dawg Sep 14 '13 at 05:50
  • with a quick look, this page looks promising: http://en.wikipedia.org/wiki/Call_stack – ash Sep 14 '13 at 05:58
  • man exams are starting from monday and all these enticing topics i'm unearthing right now ! – a dawg Sep 14 '13 at 06:04
  • so memory is allocated for local variables on the stack every time.but for static functions and variables , there ought to be a fixed space ryt? – a dawg Sep 14 '13 at 06:05
  • static functions work the same as normal functions, except that they operate on the Class instead of an instance - meaning the members referenced can only be static members, not instance members (since there is no instance known at static-method-call-time). Static variables are allocated one time - when the class is loaded, that's right. – ash Sep 14 '13 at 06:09
  • to clarify - local variables in static functions are allocated on the stack just like other functions. And static functions can be recursive. – ash Sep 14 '13 at 06:10