• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static Initializer Block  RSS feed

 
Kr. Gaurav
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We all know that "Static initializer block" executes at the Class loading time in java, and we can also call main method or normal methodp from inside the "Static initializer block"...... but here below given a sample code in which, main method is executing twice;

1st time i am calling it from inside the "Static initializer block"
But 2nd time main method get executed automatically by jvm before ending-up the execution of "Static initializer block" ( unable to get the flow of this program ??? )

As per my knowledge highlighted part of the program should execute first before 2nd time execution of main method but thts not happening here

public class StaticBlock {

static int i=10;

static {
System.out.println("my static block 1");

// You can use labeled blocks inside static blocks
printingThread:{
// static block is executed in main thread
System.out.println("Current thread "+Thread.currentThread());
}
}

static {
System.out.println("In static block "+i);
//The variables you declare in a static block aren't a part of the object. They are not
//even the static variables of the class, they just belong to that block only.
String[] arr = null;

// you can call main() too
main(arr);

// You can also execute threads
new Thread(new Runnable(){
public void run() {
for(int i=1;i<=5;i++)
System.out.println(Thread.currentThread().getName()+" "+i);
}
},"First thread").start();

// You can't do this, myMeth() is non-static
new StaticBlock().myMeth();
}


public void myMeth() {
System.out.println("In a non static method");
}


public static void main(String[] args) {

System.out.println("In main()");
}
}
 
Paweł Baczyński
Bartender
Posts: 2061
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The highlighted code will be executed before main method is executed for the second time.
By that, I mean that Thread.start() will be called before main method is executed for the second time.

After that point the output is nondeterministic as there are two running threads writing to the console at the same time.
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kr. Gaurav wrote:We all know that "Static initializer block" executes at the Class loading time in java...

It might be worth mentioning that, while all this may be fun to investigate (and don't let me stop you) static initialisers are pretty rare - mainly because there's usually a better alternative.
I think I've maybe written a dozen of 'em in 14 years.

So...don't spend too much time on this.

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!