Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static???!!!

 
Rishi Wright
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static variables and static initializers are evaluated when the class is loaded. From the JLS, §12.4.1 When Initialization Occurs:

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
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Rishi Wright
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thnx Corey and Jose I got it in JLS
rishi
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic