Java URL ClassLast Updated : 21 Mar 2026 A URL (Uniform Resource Locator) is the address used to locate resources on the Internet. In Java, the URL class provides a simple way to work with web addresses and access their components such as protocol, host, port, and file path. In this chapter, you will learn about the URL class, its constructors, methods, and example. What is URL Class in Java?The URL class is a part of the java.net package and is used to represent a Uniform Resource Locator (URL). A URL points to a resource available on the Internet. For example: Using the URL class, you can extract different parts of a URL, such as:
Example Breakdown of a URLFor the URL:
If the port number is not mentioned, Java automatically returns -1. Java URL Class ConstructorsThis class has the following constructors: 1. URL(String spec)Creates an instance of a URL from the String representation. Here is the syntax: 2. URL(String protocol, String host, int port, String file)Creates an instance of a URL from the given protocol, host, port number, and file. Here is the syntax: 3. URL(String protocol, String host, int port, String file, URLStreamHandler handler)Creates an instance of a URL from the given protocol, host, port number, file, and handler. Here is the syntax: 4. URL(String protocol, String host, String file)Creates an instance of a URL from the given protocol name, host name, and file name. Here is the syntax: 5. URL(URL context, String spec)Creates an instance of a URL by parsing the given spec within a specified context. Here is the syntax: 6. URL(URL context, String spec, URLStreamHandler handler)Creates an instance of a URL by parsing the given spec with the specified handler within a given context. Here is the syntax: URL Class MethodsThe java.net.URL class provides many methods. The most important methods of the URL class are given below.
Examples of URL ClassThe following examples demonstrate how to use the URL class to extract different parts of a URL. Example 1: Extract Basic URL InformationIn the following example, we create a URL object and retrieve its protocol, host name, port number, and file name. Output: Protocol: http Host Name: www.tpointtech.com Port Number: -1 File Name: /java-tutorial Example 2: Extract Detailed URL InformationIn the following example, we extract additional details such as default port, query string, path, and file from a URL. Output: Protocol: https Host Name: www.google.com Port Number: -1 Default Port Number: 443 Query String: q=tpointtech&oq=tpointtech&sourceid=chrome&ie=UTF-8 Path: /search File: /search?q=tpointtech&oq=tpointtech&sourceid=chrome&ie=UTF-8 Next TopicURLConnection class |
We request you to subscribe our newsletter for upcoming updates.