5

If I create a static block and create an Object there, say of some other class, will the object be created on the heap or on the stack?

class Hello {
   static {
       Abc abcObject=new Abc();
   }
   // Other Code...
} 
trincot
  • 317,000
  • 35
  • 244
  • 286
Kumar Ritesh
  • 183
  • 1
  • 2
  • 11
  • Welcome to Stack Overflow. When someone helps you here, it is customary to accept an answer. You can do this by clicking on the outline of the check mark below next to the answer you believe is correct. Thanks! – Erick Robertson Sep 04 '12 at 15:41
  • Thanks @Erick...I buy Ur Gentle Advices.. – Kumar Ritesh Sep 04 '12 at 15:50

2 Answers2

7

Objects are always on heap irrespective of static (or) non-static .

References will be on stack.

kosa
  • 65,990
  • 13
  • 130
  • 167
  • +1 `abcObject` is a local variable which is a reference to an object. This will be on the stack. The object referenced will be on the heap. – Peter Lawrey Sep 04 '12 at 15:27
  • @Nambari.. So this implies,, once the class is loaded at compile time,,,the reference abcObject(which is located on stack) will hold nothing that is Junk....But it will actually refer to the object at runtime,,that is it will actually have the memory adress at the runtime(once the object is created).....Please Answer. – Kumar Ritesh Sep 04 '12 at 15:54
  • @Kumar: I think you are half correct, because static block, your code executes at load time. So, at load time JVM creates Abc object by executing its constructor in HEAP and assigns abcObject reference to it. so, abcObject never contains reference to junk. – kosa Sep 04 '12 at 15:58
4

The object is created in the heap, but the reference to the object is in the stack.

The variable abcObject which you created is located in the stack. This contains a memory address within the heap where the new Abc() object is stored.

Erick Robertson
  • 32,125
  • 13
  • 69
  • 98
  • _reference to the object is in the stack_ can you elaborate / – Santosh Sep 04 '12 at 15:28
  • @Santosh All local variables are on the stack. – Peter Lawrey Sep 04 '12 at 15:32
  • @Erick. So this implies,, once the class is loaded at compile time,,,the reference abcObject(which is located on stack) will hold nothing that is Junk....But it will actually refer to the object at runtime,,that is it will actually have the memory adress at the runtime(once the object is created).....Please Answer..... – Kumar Ritesh Sep 04 '12 at 15:46
  • @Kumar: at compile time, `abcObject` is a reference that only has meaning within the scope of the `static { }` block. At this point, it is not located on the stack because it is still compile time. The stack is not created until runtime. But the second part is correct - it will actually refer to the object at runtime, and will actually have the memory address once the object is created. – Erick Robertson Sep 04 '12 at 16:01