*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes When static { .. } executed ? 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 "When static { .. } executed ?" Watch "When static { .. } executed ?" New topic
Author

When static { .. } executed ?

Jesu Mani
Ranch Hand

Joined: Oct 16, 2006
Posts: 34
When this code under static { .. } is executed ?

Class x {

static {
..
}
}

Masilamani A
Adeeb Abdul Karim
Greenhorn

Joined: Dec 22, 2004
Posts: 8
Static block is executed when the class is first time referred. ie.,
Statements like the ones below are executed in the JVM for the first time can trigger the execution of any static block(s).

x xx = (x)subClassObjectOfx;
OR
Class.forName("x");
OR
x xx = new x();
etc...

It will be executed only once; at the first refereance.
You can try this by giving a System.out.println in the block.

While it is loading the class to the class loader, static block is executed. A class will be loaded to the class loader only once, irrespective of how many times we use it in our programs.

Any uncaught exception in a static block will cause the program to exit with an error


�That which begins, also ends.�
rajeswari kannan
author
Ranch Hand

Joined: Oct 01, 2006
Posts: 80
It will be called during the class itsellf is loaded by the JVM. Also static blocks are executed only once.


Rajeswari Kannan Java Certification | Online Exam Software | OCAJP | OCPJP | OCEJWSD | OCEEJBD
OCEJPAD | SCJD | SCWCD | SCBCD | SCDJWS | OCMJEA | OCEJWCD | SCMAD
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi all,

as I learned last weekend, there is an exception to the above:
if a class variable is final, its call will not run the static block.

eg

will print out:
main finished, nothing else.



Yours,
Bu.


all events occur in real time
bogi raja
Greenhorn

Joined: Oct 17, 2006
Posts: 2
class Main {
public static void main(String[] args) {
int i = BadShip.rescueIslands ;
System.out.println("main finished");
}
}
class BadShip {
final static int rescueIslands=0;
static {
String md = "mayday ".toUpperCase();
for (int i=0; i<3; i++){
System.out.print(md);
}
}
}



int i = BadShip.rescueIslands ; this statement will not load the class BasdShip becaouse final fields will be in lined during compilation.so the static initializer will not be executed.

Regards,
Bogi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When static { .. } executed ?