Hi 'LL Does static varibales and static block run and stored on stack while compliling source files(i.e while making class file???)??? this was the code I was doing
class Supcls{ static int i; static{ i=20;} } the above code is stored in Supcls.java file The below code stored in Test.java and both files stored in same package(default) public class Test { static{System.out.println(Supcls.i);} } public static void main(String[] args) { Supcls supob=new Supcls(); } } when I ran the java Test it is printing the value of static var i. my question is when does the static variables /static block in Supcls initiated? thnx rishi [ August 19, 2003: Message edited by: Rishi Wright ]
A class or interface type T will be initialized immediately before the first occurrence of any one of the following: ... ... A static field declared by T is used and the reference to the field is not a compile-time constant (�15.28)...
So, as soon as a line of code is found that uses a static variable within a class, that class is loaded and any static initializers are executed. I hope that helps, Corey
The compiler gathers in textual order the intializers for static fields (*) and the code within static blocks and places them in a method called <clinit> This method is executed once after the class is loaded, but before, for example, the first instance of the class is created. JLS 12.4.1 When initialization occurs (*)the static fields that are final with a value known at compile time are not included in <clinit> . [ August 19, 2003: Message edited by: Jose Botella ]