Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static initializer

 
tony kanvas
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all

//The program prints out "5" once.
// why the program will not print 5 6 7
and we know static will execute first then the do the list I mean the constructor
thanks in advs.
 
Jay Ashar
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static initializer will be executed when the class is loaded, once you create instance of that class only instance initializer and constructors are executed, if you create multiple instance of class instance initializer and constructors are executed multiple times but static initializer will not.
 
Mayuri Son
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct me if I am wrong
When a class is loaded, first all static members are initialized, then all static blocks are executed in the order of declaration.
But when the class is instatiated then if this class is derived from some superclass
then the instance initalizer(s) of superclass(es), then constructor(s) of the superclass(es)
then instace initializer of the class and finally constructor of the class is executed. And as Hetal said static blocks are not executed at the time of instatiation only at the time of loading
 
noel angel
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In other words....It is not that the value of si did not change. The static initialization block only gets executed one time. Since this is where you put the System.println call, it is only executed once.
 
Yan Bai
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Mayuri Son:
When a class is loaded, first all static members are initialized, then all static blocks are executed in the order of declaration.

I am wondering whether there's precedence between these two. I remember they are initialized sequencially or maybe I am wrong.
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All static initialization is done in textual order. It does not matter whether you are initializing a static variable, or executing a static initialization block. For instance

prints
1
2
3
4
 
Mayuri Son
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Yan,Ron for the correction.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic