Static initializer in Java

Posted by Szere Dyeri on Stack Overflow See other posts from Stack Overflow or by Szere Dyeri
Published on 2008-12-02T20:27:36Z Indexed on 2010/05/06 17:48 UTC
Read the original article Hit count: 416

Filed under:
|
|

My question is about one particular usage of static keyword. It is possible to use static keyword to cover a code block within a class which does not belong to any function. For example following code compiles:

public class Test {
    private static final int a;    
    static {
        a = 5;
        doSomething(a);
    }
    private static int doSomething(int x) {
        return (x+5);
    }
}

If you remove the static keyword it complains because the variable a is final. However it is possible to remove both final and static keywords and make it compile.

It is confusing for me in both ways. How am I supposed to have a code section that does not belong to any method? How is it possible to invoke it? In general, what is the purpose of this usage? Or better, where can I find documentation about this?

© Stack Overflow or respective owner

Related posts about java

Related posts about static