What is the URL.getHost method in Java?

The getHost method of the URL class can be used to get the hostname of the URL object.

Syntax

public String getHost()

Parameters

This method doesn’t take any parameters.

Return value

The return type of the getHost method is a String. If the URL contains an IPv6 address instead of a domain name, then this method returns the IPv6 address enclosed in square brackets ([IPV6_address]).

The URL class is present in the java.net package.

The getHost method only returns the host name, whereas the getAuthority method returns the host name with the port number.

Code

The code below demonstrates how to use the getHost method:

import java.net.URL;
class GetHostExample {
public static void main( String args[] ) {
try {
URL url= new URL("https:// www.educative.io:8000");
String hostName = url.getHost();
System.out.println("The URL is : "+url);
System.out.println("Host name is : "+ hostName);
} catch (Exception e) {
System.out.println(e);
}
}
}

Explanation

In the code above,

  • In line number 6, we create a URL object.
URL url= new URL("https:// www.educative.io:8000");
  • In line number 7, we use the getHost method to get the host name of the URL object.
String hostName =url.getHost();
  • In lines 8 and 9, we print the URL and the host name of the URL.

Free Resources