BCA / B.Tech 6 min read

Java URL Class

Today we will read about the Java URL class, so let's get started.

The Java URL class represents a URL. The full form of URL is Uniform Resource Locator.

The Java URL class acts as a gateway to resources available on the internet.

What is a URL?

A URL is the web address of a webpage. A URL is used by the browser to open any website on the internet. Every web page of every website has a unique URL.

For example: https://notesmedia.in/topic/java-url-class-in-hindi

Where http is a protocol, notesmedia.in is a server name, and topic/java-url-class-in-hindi is the file name.

Java URL class methods:

The following methods are mainly used in the Java URL class:

  • public String getProtocol(): It returns the protocol of the URL.
  • public String getHost(): It returns the hostname of the URL.
  • public int getPort(): It returns the port number of the URL.
  • public String getFile(): It returns the filename of the URL.
  • public URLConnection openConnection(): It returns the object of URLConnection.

Using these methods, you can get various details of a URL.

Example Program:


import java.io.*;
import java.net.*;

public class URLDemo {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://notesmedia.in/topic/java-url-class-in-hindi");
            
            System.out.println("Protocol: " + url.getProtocol());
            System.out.println("Host Name: " + url.getHost());
            System.out.println("Port Number: " + url.getPort());
            System.out.println("File Name: " + url.getFile());
            
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

In this program, a URL object is initialized, and its various methods are used to print the information of the URL. If any exception occurs, it is handled in the catch block.