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.

1 comment:

  1. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.

    or learn thru JavaScript Online Training from India. Appreciating the persistence you put into your blog and detailed information you provide. Kindly keep blogging.

    ReplyDelete