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.

package com.java.connect.net;
 
import java.net.InetAddress;
import java.net.UnknownHostException;
 
//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) {
            ex.printStackTrace();
        }
    }
}

The output of the above example will be as:

Localhost's hostname is : SUDA-PC