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.

Link: https://btechgeeks.com/java-programming-examples

Here,
Protocol: https
Host Name: btechgeeks.com
File Name: java-programming-examples

In Java we have java.net.URL 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.

Approach:

  • 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.

Program:

import java.net.URL;

public class Main
{
   //Driver method
   public static void main(String args[]) throws Exception 
   {
      //Input URL
      URL u = new URL("https://btechgeeks.com/java-programming-examples/#Java_Star_Pattern_Programs");
      //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());
   }
}

Output:

URL is: https://btechgeeks.com/java-programming-examples/#Java_Star_Pattern_Programs
Protocol is: https
File part is: /java-programming-examples/
Host is: btechgeeks.com
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.