Latest News: How and What is the use of Static Block in Java - Static Block in Java Example

How and What is the use of Static Block in Java - Static Block in Java Example

 


In the Java programming language, the static method runs first then it goes to the main method.  

In the Java static block is used to check conditions first then it will execute main method. 

for example, if we try to install any application it will show some errors messages this is not supported to your pc.

Because here we already wrote static block so it will execute first and will go the main function.

Suppose our application runs only on the Windows operating system. We need to check what operating system a user is using. 

If the user is using an operating system other than "Windows," then the program terminates.

class StaticBlock {
  public static void main(String[] args) {
    System.out.println("You are using Windows_NT operating system.");
  }
 
  static {
    String os = System.getenv("OS");
    if (os.equals("Windows_NT") != true)
      System.exit(1);
  }
}


 

class StaticBlock {
  public static void main(String[] args) {
    System.out.println("Main method is executed.");
  }
 
  static {
    System.out.println("Static block is executed before main method.");
  }
}


Popular Posts

MyMarket