How To Detect Operating System In Java

In this instructional exercise, you will learn about how to detect which type of operating system you are using in your system in Java.
In the event, if you don’t know how to detect the most effective method to distinguish which sort of operating system you are utilizing in your framework or system then you are at the right place, where you will get your problem’s solution through an easy and simple example using System class in java.

How To Detect Operating System In Java

Let’s learn what System class is:-

The System class of java contains a few helpful class fields and techniques. It additionally gives offices like standard information, standard yield, and mistake yield Streams. It can’t be instantiated.

We will use the getProperty() method to which will return the property of a system that is indicated by a specified key.

The syntax is:-

public static String getProperty(String key);

You first have to import the java.lang package in your program and you can do it by:-

import java.lang.*
//which comes in the module of "java.base" and in the package of "java.lang"

You can achieve your goal through the below code:-

import java.lang.*;
public class OperatingSystemValidator
    public static String opsystem=System.getProperty("").toLowerCase();
    public static void main(String[] args)
        System.out.println("The os name is Windows");}
        else if(isUnix()){
        System.out.println("The os name is Unix");}
        else if(isSolaris()){
        System.out.println('The os name is Solaris");}
        System.out.println("operating system not supported!");}
    public static boolean isWindows(){
    return opsystem.contains("win");}

    public static boolean isMac(){
    return opsystem.contains("mac");}

    public static boolean isSolaris(){
    return opsystem.contains("sunos");}

    public static boolean isUnix(){
    return opsystem.contains("unix");}

The Result:-

windows 10
The os name is Windows

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *