Two types of initialization blocks (anonymous blocks) can be used to initialize class or instance variables in Java.
To intialize instance variables,
{} block
can be used; this block functions similar to a zero-argument constructor. It is useful in anonymous classes where a named constructor cannot be usede.g.
class testInstBlock { private double a; { a = Math.random(); } }
To initialize class variables,
static{}
block can be used, this block functions similar to a zero argument constructor for class variables. This piece of code is executed when a class is loaded by the JVM. Similar to rules for static methods, the static initializer cannot refer to instance variables–they can refer to static methods and static variables of the class.
class testStaticBlock { private static double a;static { a = Math.random(); } }