What is SystemUtils.getHostName() in Java?
Overview
getHostName() is a SystemUtils class that is used to return the host name of the system from the environment variable COMPUTERNAME on Windows or HOSTNAME on Linux.
How to import SystemUtils
The definition of SystemUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-langpackage, refer to the Maven Repository.
You can import the SystemUtils class as follows:
import org.apache.commons.lang3.SystemUtils;
Syntax
public static String getHostName()
Parameters
The method accepts no parameters.
Return value
This method returns the host name.
Code
import org.apache.commons.lang3.SystemUtils;public class Main{public static void main(String[] args){String hostName = SystemUtils.getHostName();System.out.printf("The output of SystemUtils.getHostName() is '%s'.", hostName);}}
Explanation
In the above code, we print the host name returned from the getHostName() method.
Output
The output of the code is as follows:
The output of SystemUtils.getHostName() is 'Linux-Business-PC'.
Running the above code in your system may give different outputs, depending on your machine.