Skip to main content

Java URL Class

Introduction to Java URL Class

Java URL Class is a part of Java Networking and it stands for Uniform Resource Locator. It is a pointer to a resource on the World Wide Web. A resource could be a webpage, a picture, a video, or any other type of file.

In Java, the java.net.URL class represents a URL. Java URL class provides several methods that make it a convenient tool for browsing the internet.

Creating a URL Object

To use the URL class in Java, you need to create an instance of the class. The syntax for creating a URL object is:

URL url = new URL(String spec);

Here, the spec string specifies a valid URL, including protocol (HTTP, FTP, etc.), server name (or IP address), optional port number, path of resource, etc.

For example:

URL url = new URL("http://www.example.com");

Methods of Java URL Class

Java URL Class provides various methods to play around with URL in a Java program. Some of the commonly used methods are:

  • public String getProtocol( ): It's used to get the protocol of the URL.

  • public String getHost( ): It's used to get the host name of the URL.

  • public String getFile( ): It retrieves the filename of the URL.

  • public String getPath( ): It extracts the path of this URL.

  • public int getPort( ): It's used to get the port number of the URL.

  • public String toString( ): It gives a string representation of this URL.

Example of Java URL Class

Let's use the URL class and its methods in a simple Java program.

import java.net.*;  
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.example.com:80/index.html");

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, we are first creating a URL object. Then we are using the methods of the URL class to retrieve information about the URL like the protocol, host name, port number, and file name.

Conclusion

Java URL class, part of Java Networking, is a powerful tool that allows you to connect and interact with the internet in your Java programs. It offers several inbuilt methods to retrieve and manipulate the components of a URL. Understanding and utilizing the URL class is essential for creating network-based applications in Java.