Use of a Static Block in a Class

Can anyone tell me that what is the use of a static block in a class?
e.g.

public class myclass{

    static{

        //some statements here

    }

    //some variables declared here
    //some functions defined here
}

This question was asked me in an interview. so if anyone knows the answer please give me the answer.
 

Static loop is executed, when the class is loaded.
So without creating the object we can execute this loop.
eg:
When we're loading a DB driver using Class.forName("");
The driver is registered to DriverManager class,
Using the registerDriver()method of DM.
This process done in the static loop of driver class

Got confused !!! Leave that and try this simple example
public class Stat
{
static int i=0;
static{
i=10;
System.out.println(i);
}
public static void main(String []ss)
{
}
}

Hopes you got cleared

Jim
 

If you need to do computation in order to initialize your static variables,you can declare a static block which gets executed exactly once,when the class is first loaded.

The following example shows a class that has a static method,some static variables,ana a static initialization block.

class UseStatic {
   static int a=3;
   static int b;
static void meth(int x) {
   System.out.println("x = " + x);
   System.out.println("a = " + a);
   System.out.println("b = " + b);
}

static {
  System.out.println("Static block initialized.");
  b = a * 4;
}
public static void main(String args[]) {
  meth(42);
 }

}

As soon as the UseStatic class is loaded, all of the static statements are run.First, a is set to 3, then the static block executes(printing a message),and finally, b is initialized to a* 4 or 12.Then main( ) is called,which calls meth( ), passing 42 to x. The three println( ) statements refer to the two static variables a and b,as well as to the local varible x.

Here is the output of the program:

Static block initialized.
x = 42
a = 3
b = 12

Sowbakia Nagaraj

Do you have a Java Problem?
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.