Static Initializers : static « Modifiers « SCJP






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.








3.8.static
3.8.1.static variable and method
3.8.2.Declare and uses a static counter variable
3.8.3.An example of illegal access of a nonstatic variable from a static method
3.8.4.Accessing Static Methods and Variables
3.8.5.Use the dot operator on the class name, as opposed to using it on a reference to an instance
3.8.6.An example of a redefined static method
3.8.7.static features is part of a class, not individual instance of the class.
3.8.8.You can reference a static variable via a reference to any instance of the class.
3.8.9.Static methods are not allowed to use the nonstatic features of their class.
3.8.10.A static method must specify which instance of its class owns the variable or executes the method.
3.8.11.Static Initializers
3.8.12.Non-static methods may access both static and non-static variables.
3.8.13.Nested classes can be declared static, in which case they belong to the class as a whole, not any particular instance.