File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static???!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static???!!!" Watch "static???!!!" New topic


Rishi Wright
Ranch Hand

Joined: Jun 25, 2003
Posts: 46
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 file
The below code stored in and both files stored in same package(default)
public class Test {
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?
[ August 19, 2003: Message edited by: Rishi Wright ]
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
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,

SCJP Tipline, etc.
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
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 ]

SCJP2. Please Indent your code using UBB Code
Rishi Wright
Ranch Hand

Joined: Jun 25, 2003
Posts: 46
Thnx Corey and Jose I got it in JLS
I agree. Here's the link:
subject: static???!!!
It's not a secret anymore!