Luchian Grigore
Luchian Grigore

Reputation: 258558

Java syntax question

What does

static{
    //something
}

declared inside a class definition body mean?

public class A extends B{
     static {
          C.register(new C(A.class,
                    (byte) D.x.getCode()) {
                         public DataSerializable newInstance() {
                              return new A();
                         }
                    }
               );
     }
 }

Upvotes: 5

Views: 151

Answers (6)

Nicktar
Nicktar

Reputation: 5575

It's a static initializer. It's run once the class is loaded and it's results can be stored in static members. It's used to initialize static members that require more than the regular new Xyz() (like Lists or Maps)...

Upvotes: 2

bobsv
bobsv

Reputation: 11

It means that you will have this section which is inside the static block extecuted FIRST on load of the class into the JVM.

Execute the following simple program might make things clearer

public class Test123 {
  static{
    System.out.println("Hello from static block");
  }

  public static void main(String[] args) {
    System.out.println("In main");
  }
}

The output to the above will be

Hello from static block 
In main

Upvotes: 1

Jack Edmonds
Jack Edmonds

Reputation: 33161

The static block is called a "static initialization block." It is very similar to a regular constructor except that it can only initialize static variables.

I have found it to be useful when initialization of some static variable may throw an exception that you would like to handle or at least log. It is especially useful in the initialization of static final variables.

You may read more about static initialization blocks here: Initializing Fields

Upvotes: 6

Dhruv Gairola
Dhruv Gairola

Reputation: 9182

That becomes a static initialisation block, which can be written as a static method.

Upvotes: 2

Nathan Hughes
Nathan Hughes

Reputation: 96385

It's a static initializer. It lets you specify things that happen at the time that the class is loaded, before any instance is created.

If an exception is thrown from a static initializer it's very confusing, it's hard to tell where it came from. Anything that you do in a static initializer should have a try-catch around it and have the exception get logged. It's a good language feature to avoid if you can.

Upvotes: 1

Ilya Saunkin
Ilya Saunkin

Reputation: 19800

It executes a block of code without requiring an instance of this class, i.e. as soon as the class loader loads the class.

Upvotes: 3

Related Questions