You are here

Java static block program

Java programming language offers a block known as static which is executed before the main method runs. Below is the most straightforward example to understand the functioning of a static block, later we will see the practical use of a static block.

Java static block program

  1. class StaticBlock {
  2.   public static void main(String[] args) {
  3.     System.out.println("Main method is executed.");
  4.     }
  5.  
  6.   static {
  7.     System.out.println("Static block is executed before main method.");
  8.   }
  9. }

Output of the program:
Java static block program

A static block can be used to check conditions before execution of the main begins, Suppose we have developed an application which runs only on Windows operating system then we need to check what operating system is installed on a user machine. In our Java code, we check which operating system is installed on a user machine, if a user is using an operating system other than "Windows" then the program terminates.

  1. class StaticBlock {
  2.   public static void main(String[] args) {
  3.     System.out.println("You are using Windows_NT operating system.");
  4.   }
  5.  
  6.   static {
  7.     String os = System.getenv("OS");
  8.     if (os.equals("Windows_NT") != true)
  9.       System.exit(1);
  10.   }
  11. }

We are using getenv method of System class which returns value of an environment variable which is passed as an argument to it. Windows_NT is a family of operating systems which includes Windows XP, Vista, Windows 7, Windows 8 and others.

Output of the program on Windows 7:
Java static block program output