File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Simple static block - but how it works ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Simple static block - but how it works ??" Watch "Simple static block - but how it works ??" New topic

Simple static block - but how it works ??

prasanna kanth

Joined: May 14, 2006
Posts: 28

Can someone explain, how this static block works here, is it a kind of constructor ??
What is the use of static block here and how it behaves ?

It's printing super and two as output !!

John Dell'Oso
Ranch Hand

Joined: Apr 08, 2004
Posts: 130
Static blocks aren't constructors. These blocks of code are executed only if required - that is when a static method or field of the class is accessed or if an object is being created for the first time. In your example, the object of type Two is being created - it's super class is Super, so its static block is executed, then control passes back to the Two class and its static block is executed - this results in the output you're observing.

I've been out of the Java "loop" for a while - I'm sure someone will correct me if I'm wrong or articulate a better response.

Saifuddin Merchant
Ranch Hand

Joined: Feb 08, 2009
Posts: 607

A static block is executed when the class is loaded for the first time.
In your case the class Two gets loaded when you create a new object resulting in the output super and two. I'm not a 100% if the order of the output will always be 'super' followed by 'two' and not the other way around.

A static block is an initialization block that runs just once when the class is loaded for the first time (and so could be considered as a Class Level Constructor). Typically static blocks would be used to initialize static/singleton variables.

Cheers - Sam.
Twisters - The new age Java Quiz || My Blog
Monu Tripathi

Joined: Oct 12, 2008
Posts: 1369

Static blocks are executed when a class is initialized.A class is initialized either
1. when you instantiate it OR
2. when you execute a static method of the class OR...well... Read JLS 12.4 for all the scenarios!

Also, when a class is initialized its direct super class needs to be initialized first.
In your application, you instantiated an object of class Two. So, first the super class was initialized(and therefore its static block was executed) followed by initialization of class Two.

That explains the output, I guess.


[List of FAQs] | [Android FAQ] | [Samuh Varta]
prasanna kanth

Joined: May 14, 2006
Posts: 28
Thanks a lot folks
I actually got it how it works

Can someone explain with the practical scenario when its actually and normally used !!

I agree. Here's the link:
subject: Simple static block - but how it works ??
It's not a secret anymore!