• Post Reply Bookmark Topic Watch Topic
  • New Topic

static block  RSS feed

 
Duc Ta
Ranch Hand
Posts: 46
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have one question about static block code in Java
package Chapter03;



The output after the preceding code is run:

1st static init
2nd static init
Run
1st instance init
2nd instance init
no-arg const
1st instance init
2nd instance init
1-arg const


I think that the output should be:
Run
1st static init
2nd static init
1st instance init
2nd instance init
no-arg const
1st instance init
2nd instance init
1-arg const


because the code to print "Run" in the begining of main() method

Can anyone explain to me?



 
Santosh Kumar Nayak
Ranch Hand
Posts: 193
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1)Static block before even object creation
2)Main program : hence your SOP prints Run

Remember that in every constructor, if the very first statement is not this(), then compiler implicitly inserts a call to super() as a very first statement.
Upon instantiation, after the call to super() completes, instance initializer blocks run, and then the remaining statements in the constructor run.
 
Santosh Kumar Nayak
Ranch Hand
Posts: 193
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Refer to this for Clarification.

https://www.javatpoint.com/instance-initializer-block
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That tutorial tells us lots about instance initialisers but little about static initialisers.
I think you shou‍ld use one and only one initialiser per type per class; unlike methods which don't have an order of execution, initialisers do: from top to bottom. To avoid confusion use one initialiser.
Static initialisers are executed when the class is loaded; you need the Class<Init> object in place to run the main method, so the Init class has to be loaded first. When it is loaded the static initialisers are executed in the order they are written. When the class has been loaded, the main method can be run, then the superclass' constructor, and last the current class' constructor. Remember that the instance initialisers are copied into the constructors.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!