How to get a localhost hostname in java

This example shows you how to get the hostname of your localhost in java.

Below is the example code of getting hostname of localhost in java.

//How to get a localhost hostname in java
public class LocalhostHostnameExample {
    public static void main(String[] args) {
        try {
            // Get the InetAddress of your localhost
            InetAddress address = InetAddress.getLocalHost();
            // Print the hostname
            System.out.println("Localhost's hostname is : "
                    + address.getHostName());
        } catch (UnknownHostException ex) {

The output of the above example will be as:

Localhost's hostname is : SUDA-PC