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

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

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;
x xx = new x();

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
MyExamCloud Software Support
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
MyExamCloud for Java SE Certifications, Java EE Certifications and Java ME Certification Preparation.
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.


will print out:
main finished, nothing else.


all events occur in real time
bogi raja

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++){

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

It is sorta covered in the JavaRanch Style Guide.
subject: When static { .. } executed ?
It's not a secret anymore!