How to detect Operating System using Java code


If you have a Java Application that is supposed to run on various operating system (Windows, macOS, Linux etc) it becomes very important to know which underlying operating system is the code executing to set options like - directory structure, file system, end of line encoding (CL, RF, CLRF) etc,

Java code to detect Operating System (OS):

/**
 * 
 * Detect Java OS
 * 
 */
public class Example {

    public static void main(String[] args) {

        String os = getOperatingSystemDetails();

        if(os.contains("Windows")) {
            System.out.println("Your Operating System is - Windows");
        } else if (os.contains("Mac OS X")) {
            System.out.println("Your Operating System is - macOS");
        } else if  (os.contains("Linux")) {
            System.out.println("Your Operating System is - Linux"); 
        } else {
            System.out.println("Your Operating System is " + os);
        }

    }

    /**
     * This Method returns the underlying OS where
     * the Java code run.
     * 
     * @return the Operating System name as a String
     */
    public static String getOperatingSystemDetails() {
        return System.getProperty("os.name");

    }

}
Output:

Your Operating System is - macOS

Detect Underlying Operating System using Java Code
Detect Underlying Operating System using Java Code
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.