DEV Community

GAURAV KUMAR
GAURAV KUMAR

Posted on

Get The Underlying OS on which the program is running in Java

You may want to know the operating system on which your Java program is running because you want to

  1. Implement platform-specific behavior → Let’s say you need to construct a file path in your program. But the ways in which file paths are constructed on Windows and Unix-based systems are different. Knowing the OS on which the program is running may help you implement a robust solution that works on different systems.
  2. Use a platform-specific library → There are some libraries that work only on a particular OS. So, you want to know whether you can use one library in your program.
  3. Access System Properties → There are some system properties that have different values on different operating systems. Such as the default temporary directory or the user home directory. Knowing the OS may help you access these values correctly.

If you have any of the above-mentioned use cases or any other use cases, but you want to know the OS on which your programming is running, you are in the right place.

Hi! I’m Gaurav Kumar, and you’re welcome to "Re-Inventing the Wheel". Now, without further ado, let's see the code that will tell us about the OS on which it’s running.

Below is the code snippet to know the underlying OS on which it’s running.

String os = System.getProperty("os.name");
System.out.println("OS: " + os);
Enter fullscreen mode Exit fullscreen mode

Note: The string inside the getProperty() method is case-sensitive. Make sure that each letter used is in lowercase; otherwise, it returns **null**.

Other ways to determine the OS

  1. Using System.getenv method

    String os = System.getenv("OS");
    System.out.println("OS: " + os);
    

    This code works fine on Windows. However, this code is not portable as the OS environment variable is not present by default on many other operating systems, such as Linux and Mac OS.

  2. Using Runtime.exe method

    Process p = Runtime.getRuntime().exec("uname -s");
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String os = reader.readLine();
    System.out.println("Operating system: " + os);
    

    This code executes the uname -s command, which returns the name of the operating system on Unix-based systems. However, this approach is not portable, as the uname command may not be available on all operating systems.

Conclusion

The most reliable way to know the OS on which a program is running is to use System.getProperty method that works on all the operating systems.

At the end, I would like to take this opportunity to thank you for reading this article until the end.

Happy Coding 😀!

See you soon!

Top comments (0)