How to Use Static Blocks in Java

In the Java programming language, a block is a group of lines of code enclosed in curly braces. Blocks serve many purposes in Java--for instance, control Java keywords such as "while" take a block as an argument. In particular, Java supports "static blocks." A static block gets executed exactly once per class--rather than once per object created in the class, as would be the case for code included in a constructor method. You can use static Java blocks to perform one-time tasks when the class in question gets loaded into memory by the Java Virtual Machine.

Instructions

    • 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;

      }

      }

Related Searches:

References

Comments

Related Ads

Featured