• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When will be a static block executed.

 
Venkata Sirish
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Even though after hard google search, i could not find when a static block will be executed and how many times.



Thanks in Advance,
Guru
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Once, when the class loads.
 
Rob Spoor
Sheriff
Pie
Posts: 20494
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the order they are defined, from top to bottom.
 
Venkata Sirish
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks dudes for replying,

I have a one more doubt. will the static block be executed as many times as the same class objects(different multiple) are loaded into memory.
 
Manuel Leiria
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it's static, it will be loaded only one time
 
Guido Sautter
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
... unless you load the class multiple times through multiple different class loaders ... then the static blocks will be executed every time you load the class.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Venkata Guru:
...will the static block be executed as many times as the same class objects(different multiple) are loaded into memory.

I'm not sure what you mean.

The static code executes when a class is loaded. After that, you can use the class to create as many objects as you wish, but the class is only loaded once.
 
manisha verma
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you are confusing init block and static block, static block runs every time a class gets loaded and init block runs every tiem a new instance is created just before the call to super constructor is made.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic