I came across this Java code:
static {
String aux = \"value\";
try {
// some code here
} catch (Exception e) { }
String UUID_prefix =
This is called a static initialization block and will be executed once, when this class gets loaded.
This is the block of code that will get invoked when your class is loaded by classloader
Sufyan,
Static initializers aren't inherited and are only executed once when the class is loaded and initialized by the JRE. That means this static block will be initialized only once irrespective of how many objects you have created out of this class.
I am not a big fan of it and i am sure there are better alternatives for it depending on the situation.
Thanks, Reds
This syntax has been outdated as of Java 7. Now the equivalent is:
public static void main(String[] args) {
/*
stuff
*/
}
This is a static initializer block. You must have found it in a class's body outside of any method. The static init block runs only once for each class, at classload time.
This is a static initialization block. Think of it like a static version of the constructor. Constructors are run when the class is instantiated; static initialization blocks get run when the class gets loaded.
You can use them for something like this (obviously fabricated code):
private static int myInt;
static {
MyResource myResource = new MyResource();
myInt = myResource.getIntegerValue();
myResource.close();
}
See the "Static Initialization Blocks" section of Oracle's tutorial on initializing fields.