How is memory allocation/management done for final variables ?? And say I have an interface TestInterface where in I define a few constants which are static and final by default. And I have more than one class implementing this interface. The memory for static variables is allocated when the class is first loaded by the class loader. In the above scenario how is the memory allocation done for the constants ??
There is only ever one copy of static variables (final or not), unless you are in an environment that may reload classes (such as a J2EE container during hot deployment). In addition, static final variables of primitive type can be inlined during compilation. For example, if you define static final int MYCONSTANT = 137, then using MYCONSTANT in code is the same as using the literal 137. Memory allocation for final instance variables does not differ from that of non-final variables. There is a nice twist with final local variables and inner classesIt looks as if the anonymous Runnable created in this method can simply access the "number" method parameter, but that isn't really true. It has an implicit instance variable that is a copy of the "number" method parameter. So although it seems as if there is only one integer in this code, there are in fact two. Had "number" been an object reference, it would only have been the reference which was duplicated, not the object itself. So there's no big impact on memory allocation here. - Peter [ January 30, 2003: Message edited by: Peter den Haan ]