hi, what is the practical use of such a block of code? public class Test { static {int a = 5; } public static void main(String args[]) { System.out.println(a);//illegal as a cannot be accessed out of the static block } } Regards, Kapil
Hope this helps. Correct me if I am wrong.<p>Cheers <img src="smile.gif" border="0"> ,<br />Kapil
Static initializers are useful if you need to do something before class instaces are created. Typical usage is to initialize static members. For example, if your class had a static ConnectionHandle to a databse connection, you can establish the connection and initialize the handle in the static block. About you error, the variable 'a' is declared within the static block and hence it is a local variable visible only within that block.
Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Hi Kapil There is no use of defining variables inside static initializes as scope of that variable is only inside static block. Basically static initializes get executed ONLY once when class is first loaded by JVM (before creating any instance of it). There are many use of static initializes�like (1) To initialize static variables and static final variables. The static block executes only once when class is first loaded by JVM. It can�t pass checked Exception (2) As Ajith said to establish database Connection (3) To load libraries for native methods.
Humans and their filthy friendship brings nothing but trouble. My only solace is this tiny ad:
a bit of art, as a gift, the permaculture playing cards