Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When static { .. } executed ?

 
Jesu Mani
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When this code under static { .. } is executed ?

Class x {

static {
..
}
}

Masilamani A
 
Adeeb Abdul Karim
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
rajeswari kannan
MyExamCloud Software Support
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It will be called during the class itsellf is loaded by the JVM. Also static blocks are executed only once.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
bogi raja
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic