This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes When will be a static block executed. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "When will be a static block executed." Watch "When will be a static block executed." New topic
Author

When will be a static block executed.

Venkata Sirish
Ranch Hand

Joined: Apr 09, 2007
Posts: 112
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

Joined: Aug 31, 2004
Posts: 11343

Once, when the class loads.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19656
    
  18

In the order they are defined, from top to bottom.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Venkata Sirish
Ranch Hand

Joined: Apr 09, 2007
Posts: 112
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

Joined: Jul 13, 2007
Posts: 171
If it's static, it will be loaded only one time


Manuel Leiria<br /> <br />--------------<br />Peace cannot be kept by force; it can only be achieved by understanding. <br /> Albert Einstein
Guido Sautter
Ranch Hand

Joined: Dec 22, 2004
Posts: 142
... 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

Joined: Aug 31, 2004
Posts: 11343

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

Joined: Jun 28, 2007
Posts: 10
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: When will be a static block executed.
 
Similar Threads
static block
Static initializer...
Confuse in static block
constructor invocation order/priority
static block