Java Program to Get the Parts of an URL

In this article you will see how to get the different components of URL by using Java programming language.

Java Program to Get the Parts of an URL

Uniform Resource Locator in short it is called as URL which is used to uniquely identify a resource on the internet. An URL has many forms but in general they follow these 4 forms.

  1. Protocol
  2. Hostname
  3. File Name
  4. Port Number(Optional)

Lets see an example.


Protocol: https
Host Name:
File Name: java-programming-examples

In Java we have class which acts as an resource locator in WWW(World Wide Web). There are many methods of URL class like-

  • public String getProtocol(): Returns the protocol of the URL
  • public String getPort(): Returns the Port Number of the URL
  • public String getHost(): Returns the host name of the URL
  • public String getFile(): Returns the file name of the URL
  • public String getDefaultPort(): Returns the default port of the URL

Let’s see the program to understand it more clearly.


  • Create the object of URL and pass the input URL as parameter.
  • By using the URL object call the respective inbuilt methods of URL class.
  • Get the result.



public class Main
   //Driver method
   public static void main(String args[]) throws Exception 
      //Input URL
      URL u = new URL("");
      //String representation of the URL
      System.out.println("URL is: " + u);
      //Get the Protocol
      System.out.println("Protocol is: " + u.getProtocol());
      //Get the File name
      System.out.println("File part is: " + u.getFile());
      //Get the Host name
      System.out.println("Host is: " + u.getHost());
      //Get the Path
      System.out.println("Path is: " + u.getPath());
      //Get the Port
      System.out.println("Port is: " + u.getPort());
      //Get the Default port
      System.out.println("Default port is: " + u.getDefaultPort());


URL is:
Protocol is: https
File part is: /java-programming-examples/
Host is:
Path is: /java-programming-examples/
Port is: -1
Default port is: 443

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.