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.
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-lang
package, refer to the Maven Repository.
You can import the SystemUtils
class as follows:
import org.apache.commons.lang3.SystemUtils;
public static String getHostName()
The method accepts no parameters.
This method returns the host name.
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);}}
In the above code, we print the host name returned from the getHostName()
method.
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.