1. Introduction

There are a couple of ways to figure out the OS on which our code is running on.

In this brief article, we’re going to see how to focus on doing OS detection in Java.

2. Implementation

One way is to make use of the System.getProperty(os.name) to obtain the name of the operating system.

The second way is to make use of SystemUtils from the Apache Commons Lang API.

Let’s see both of them in action.

2.1. Using System Properties

We can make use of the System class to detect the OS.

Let’s check it out:

public String getOperatingSystem() {
    String os = System.getProperty("os.name");
    // System.out.println("Using System Property: " + os);
    return os;
}

2.2. SystemUtils – Apache Commons Lang

SystemUtils from Apache Commons Lang is another popular option to try for. It’s a nice API that gracefully takes care of such details.

Let’s find out the OS using SystemUtils:

public String getOperatingSystemSystemUtils() {
    String os = SystemUtils.OS_NAME;
    // System.out.println("Using SystemUtils: " + os);
    return os;
}

3. Result

Executing the code in our environment gives us the same result:

Using SystemUtils: Windows 10
Using System Property: Windows 10

4. Conclusion

In this quick article, we saw how we can find/detect the OS programmatically, from Java.

As always, the code examples for this article are available over on GitHub.