This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
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
Author

static???!!!

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 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

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,
Corey


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
rishi
 
GeeCON Prague 2014
 
subject: static???!!!