public class MainClass {
static double d = 1.23;
static {
System.out.println("Static code: d=" + d++);
}
public static void main(String args[]) {
System.out.println("main: d = " + d++);
}
}
Static code: d=1.23
main: d = 2.23
Static initializers are used to perform processing when a class is first loaded.
static initializers are executed only once.
Static initializers are identified by the static keyword followed by code surrounded in curly brackets.
class MainClass{
static String s = "This code is executed second.";
String t = "This code is executed last.";
static { // Static initializer
display("This code is executed first.");
}
public static void main(String[] args) {
display(s);
MainClass app = new MainClass();
app.display(app.t);
}
static void display(String s) {
System.out.println(s);
}
}
This code is executed first.
This code is executed second.
This code is executed last.
|