Static and Object Initializers

Static and Object Initializers

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,


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();	  }	}

See also  Small Business Strategies with Venmo

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist