To detect the operating system (OS) in Java, you can use the System.getProperty()
method and get the value of the os.name
system property. This property returns a string that represents the name of the OS.
Here's an example of how to use the System.getProperty()
method to detect the OS:
String os = System.getProperty("os.name"); if (os.contains("Windows")) { // OS is Windows } else if (os.contains("Mac")) { // OS is Mac } else if (os.contains("Linux")) { // OS is Linux } else { // OS is unknown }
The above code gets the value of the os.name
system property and checks if it contains the string "Windows", "Mac", or "Linux". This allows you to determine the OS of the system.
Note that the os.name
property may not always return the exact name of the OS. For example, it may return "Windows 10" instead of just "Windows". It is recommended to use a library or service that provides more reliable OS detection, such as the User-Agent string or the W3C Device Detection API.