Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
java.net.Proxy Class in Java
Next article icon

java.net.URL Class in Java

Last Updated : 03 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

URL is an acronym of Uniform resource locator. It is a pointer to locate resource in www (World Wide Web). A resource can be anything from a simple text file to any other like images, file directory etc. 

The typical URL may look like

http://www.example.com:80/index.html

The URL has the following parts:

  • Protocol: In this case the protocol is HTTP, It can be HTTPS in some cases
  • Hostname: Hostname represent the address of the machine on which resource is located, in this case, www.example.com
  • Port Number: It is an optional attribute. If not specified then it returns -1. In the above case, the port number is 80.
  • Resource name: It is the name of a resource located on the given server that we want to see

You can learn more about the URL here.

The Class structure of the URL is as shown below:

public final class java.net.URL extends java.lang.Object

The Following are constructors provided by the URL class.

Constructor

Explanation

public URL(String  url ) This constructor creates an object of URL class from given string representation
public URL(String  protocol, String  host, int  port, String  file) This constructor creates an object of URL from the specified protocol, host, port number, and file.
public URL(String  protocol, String  host, String  file) This constructor creates an object of URL from the specified protocol, port number, and file. The default port number is used in this case.
public URL(URL  context, String  src) This constructor creates an instance of a URL by parsing the given src with the specified handler within a given context.

Methods Provided by URL Class:

Method  Explanation
equals(Object obj) This method compares this URL for equality with another object.
getAuthority() This method gets the authority part of this URL.
getContent() This method gets the contents of this URL.
getContent(Class[] classes) This method gets the contents of this URL.
getDefaultPort() This method gets the default port number of the protocol associated with this URL.
getFile() This method gets the file name of this URL.
getHost() This method gets the hostname of this URL, if applicable.
getPath() This method gets the path part of this URL.
getPort() This method gets the port number of this URL.
getProtocol() This method gets the protocol name of this URL.
getQuery() This method gets the query part of this URL.
getRef() This method gets the anchor (also known as the “reference”) of this URL.
getUserInfo() This method gets the userInfo part of this URL.
hashCode() This method creates an integer suitable for hash table indexing.
openConnection() This method returns a URLConnection instance that represents a connection to the remote object referred to by the URL.
openConnection(Proxy proxy) Same as openConnection(), except that the connection will be made through the specified proxy; Protocol handlers that do not support proxing will ignore the proxy parameter and make a normal connection.
openStream() This method opens a connection to this URL and returns an InputStream for reading from that connection.
sameFile(URL other) This method compares two URLs, excluding the fragment component.
set(String protocol, String host, int port, String file, String ref) This method sets the fields of the URL.
set(String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref) This method sets the specified 8 fields of the URL.
setURLStreamHandlerFactory(URLStreamHandlerFactory fac) This method sets an application’s URLStreamHandlerFactory.
toExternalForm() This method constructs a string representation of this URL.
toString() This method constructs a string representation of this URL.
toURI() This method returns a URI equivalent to this URL.

Demonstration 1

In this demonstration, we are going to create an object of URL class for a given String URL, and we are going to print hostname, protocol, filename and Port number for given URL.

Java




// importing package required
import java.net.URL;
import java.util.Scanner;
 
class GFG {
    public static void main(String[] args)
    {
        String url
            = "https://www.geeksforgeeks.org/variables-in-java/";
        // Calling method to get URL info
        getUrlInfo(url);
    }
    static void getUrlInfo(String url_string)
    {
        // Creating object of URL class
        try {
            URL url = new URL(url_string);
 
            System.out.println("Hostname: "
                               + url.getHost());
            System.out.println("Port Number: "
                               + url.getPort());
            System.out.println("File name: "
                               + url.getFile());
            System.out.println("Protocol:  "
                               + url.getProtocol());
        }
        catch (Exception e) {
        }
    }
}
 
 
Output
Hostname: www.geeksforgeeks.org Port Number: -1 File name: /variables-in-java/ Protocol:  https


Next Article
java.net.Proxy Class in Java

S

shrikantdaund
Improve
Article Tags :
  • Java
  • Java-net-package
  • Java-URL
Practice Tags :
  • Java

Similar Reads

  • java.net.Proxy Class in Java
    A proxy is an immutable object and type of tool or application or program or system, which helps to protect the information of its users and computers. It acts as a barrier between computer and internet users. A Proxy Object defines the Proxy settings to be used with a connection. Proxy servers are
    3 min read
  • java.net.URLConnection Class in Java
    URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction wi
    5 min read
  • java.net.Socket Class in Java
    The java.net.Socket class allows us to create socket objects that help us in implementing all fundamental socket operations. We can perform various networking operations such as sending, reading data and closing connections. Each Socket object that has been created using with java.net.Socket class h
    5 min read
  • java.rmi.Naming Class in Java
    Java.rmi.Naming class contains a method to bind, unbind or rebind names with a remote object present at the remote registry. This class is also used to get the reference of the object present at remote registries or the list of name associated with this registry. Syntax: Class declaration public fin
    4 min read
  • java.net.ProtocolFamily Class in Java
    ProtocolFamily is a java Interface. The java.net.ProtocolFamily represents a family of communication protocols. Java.net.StandardProtocolFamily implements ProtocolFamily Interface. public interface ProtocolFamily Methods of java.net.ProtocolFamily java.net.ProtocolFamily interface contains only one
    2 min read
  • java.net.NetPermission Class in Java
    NetPermission class is used to allow network permissions. NetPermission class extends BasicPermission class. It is a “named” permission i.e it contains a name but no action. Permission nameWhat permission allowsRisks associated with this permissionallowHttpTraceThis permission allows using the HTTP
    5 min read
  • Java.lang.Runtime class in Java
    In Java, the Runtime class is used to interact with Every Java application that has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method. Methods of Java
    6 min read
  • java.net.SocketOption Class in Java
    The java.net.SocketOption is a socket option that is connected with a socket, as the set of channels packages is java.nio.channels.NetworkChannel that this interface has defined the setOption as well as the getOption methods to set and query's the channels within its Socket Options. --> java.net
    5 min read
  • Object Class in Java
    Object class in Java is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of the Java Object class and if it extends another class then it is indirectly derived. The Ob
    8 min read
  • java.net.InetAddress Class in Java
    public class InetAddress extends Object implements Serializable: The java.net.InetAddress class provides methods to get the IP address of any hostname. An IP address is represented by 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses. There are 2 types of address
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences