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?
when a developer use an initializer block, the Java Compiler copies the initializer into each constructor of the current class.
Example:
the following code:
is equivalent to:
I hope my example is understood by developers.
Uff! what is static initializer?
The static initializer is a
static {}
block of code inside java class, and run only one time before the constructor or main method is called.OK! Tell me more...
static { ... }
inside any java class. and executed by virtual machine when class is called.return
statements are supported.this
orsuper
are supported.Hmm where can I use it?
Can be used anywhere you feel ok :) that simple. But I see most of the time it is used when doing database connection, API init, Logging and etc.
Don't just bark! where is example?
Output???
Hope this helps!