How to Use Static Blocks in Java

104 13
    • 1). Define the class where you want the static block to be, as in the following sample code:

      public class PairOfInts {

      static int x,y;

      static String status = "Global initialization not yet done";

      public PairOfInts(int a,b) {

      x=a;

      y=b;

      }

      }

    • 2). Add the delimiters for the static block inside the class definition, as in the following sample code:

      public class PairOfInts {

      static int x,y;

      static String status = "Global initialization not yet done";

      static {

      }

      public PairOfInts(int a,b) {

      x=a;

      y=b;

      }

      }

    • 3). Add the one-time initialization code between the static block delimiters, as in the following sample code:

      public class PairOfInts {

      static int x,y;

      static String status = "Global initialization not yet done";

      static {

      // Will execute at most once per execution of the Java application

      status = "Global initialization done";

      }

      public PairOfInts(int a,b) {

      x=a;

      y=b;

      }

      }

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.