6

All the objects of a class share the static variable. But when is the memory allocated for the static variable? Is it when the first object is created for the class? Or does it happen even before any instance for the class is created? Also instance variable is allocated memory at runtime. The memory for static variable is allocated at runtime or compile time?

that other guy
  • 116,971
  • 11
  • 170
  • 194
Amriteya
  • 1,118
  • 15
  • 37
  • This is an implementation detail. Do you have a particular implementation or guarantee you're wondering about? – that other guy Jun 29 '15 at 07:56
  • It is [definitively not at compile-time](http://stackoverflow.com/questions/4343760/when-is-static-variable-loaded-in-java-runtime-or-compile-time). It is before the first object gets created (you can access static field/methods without creating an instance of this class). My intuition tells me that those are allocated as the class gets loaded. – Turing85 Jun 29 '15 at 07:56
  • this is exactly what you want to know http://stackoverflow.com/questions/6569557/what-is-the-actual-memory-place-for-static-variables – Ashish Shetkar Jun 29 '15 at 08:00
  • 1
    One minor detail: *All the objects of a class share the static variable.* This is a misinterpretation. Static fields belong to the class, not the instances. You can, however, access them from the instances of the class. With this view, it is intuitive that static fields are allocated when the class is loaded. – Turing85 Jun 29 '15 at 08:02
  • possible duplicate of [Whats up with static memory in java?](http://stackoverflow.com/questions/405364/whats-up-with-static-memory-in-java) – Rajesh Jun 29 '15 at 08:06

2 Answers2

3

When the class is loaded, at runtime. You can find the details here.

Turing85
  • 18,217
  • 7
  • 33
  • 58
Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

when class loader loads the class, memeory for all static variables will be allocated and this will be done only once

Pavan Kumar K
  • 1,360
  • 9
  • 11