Find user's operating system (OS) using java code and understand the static block.

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

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

public class FindOS {

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


Output from Windows OS:

You are using Windows operating system.

No comments:

Post a Comment