Static block in Java
Java programming language offers a block known as static that runs before the execution of the main method. Below is an example to understand its functioning. Later, we see its practical use.
Java static block program
public static void main(String[] args) {
System.out.println(“Main method is executed.”);
}static {
System.out.println(“Static block is executed before main method.”);
}
}
Output of the program:
A static block is used to check conditions before the execution of the main begins. 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.
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);
}
}
We are using the getenv method of System class that returns the value of an environment variable, which we pass as an argument to it. Windows_NT is a family of operating systems that include Windows XP, Vista, Windows 7, Windows 8, and others.
Output of the program on Windows 7: