I came across this Java code:
static {
String aux = "value";
try {
// some code here
} catch (Exception e) { }
String UUID_prefix = aux + ":";
}
I am new to Java, please explain what is happening here.
I came across this Java code:
static {
String aux = "value";
try {
// some code here
} catch (Exception e) { }
String UUID_prefix = aux + ":";
}
I am new to Java, please explain what is happening here.
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.
This is the block of code that will get invoked when your class is loaded by classloader
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.
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 is called a static initialization block and will be executed once, when this class gets loaded.
This syntax has been outdated as of Java 7. Now the equivalent is:
public static void main(String[] args) {
/*
stuff
*/
}