

{"id":12711,"date":"2018-04-07T17:42:21","date_gmt":"2018-04-07T17:42:21","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=12711"},"modified":"2026-05-28T16:05:26","modified_gmt":"2026-05-28T10:35:26","slug":"java-url-class","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/java-url-class\/","title":{"rendered":"Learn Java URL Class With Examples"},"content":{"rendered":"<p>In programming, we frequently need to work with URLs. But what are URLs anyway? Sounds complex. The full form of URL is Uniform Resource Locator.<\/p>\n<p>So from the full form, we can understand that in order to access any resource on the internet, we need to have URLs. But if you see in the address bars of your browsers, you will observe that the URLs are very long strings with random characters and incomprehensible hashes.<\/p>\n<p>However, we do need to parse and extract useful information from URLs in our everyday lives. How do we do that? Java is the answer.<\/p>\n<h3>URL Class in Java<\/h3>\n<p>The URL class in Java allows us to get the resources from the dynamic webpages that are on the internet. It gives the information related to the specific URL. Taking out the method name, host, port, and the protocol present on the URL can be retrieved by using the URL class. Certain methods are defined in the URL class to get the information. To use the URL class, import the java.net package.<\/p>\n<p>Take an example of the following URL.<br \/>\n<strong>https:\/\/data-flair.training\/<\/strong><\/p>\n<p>Let us understand what makes up the URL.<\/p>\n<p>A typical URL will consist of a protocol, a hostname, a file name, and a port number.<\/p>\n<p>When you look at the URL, you will observe that the URL begins with HTTPS. This is the protocol of connection with the server. There are many protocols, such as HTTP, HTTPS, FTP, and so on\u2026<\/p>\n<p>You may read about these protocols later. For now, let us consider a very abstract definition of it. Let us assume that the protocol is basically a set of rules that the client and the server have to follow in order to transfer data between them.<\/p>\n<p>The next part of the URL is the domain name. This is basically the name of the website. In our case, this is data-flair.training.<br \/>\nThis is a unique name given to each website.<\/p>\n<p>Now take a look at this URL right here: <strong>https:\/\/data-flair.training\/blogs\/java-tutorial\/<\/strong><\/p>\n<p>The slashes mark directories through which you can find the file you are looking for. The file name can be any file depending on the website you are visiting. You can choose to open a PHP file, an HTML file, or a simple \u201ctext\u201d file too.<\/p>\n<p>This depends on the web server entirely. The port basically indicates which port on the web server we are connecting to. By default, the web browsers connect to port 80, which is generally configured by a web server to serve webpages.<\/p>\n<p>Enough about URLs for now.<\/p>\n<p>Let us look at the class Java provides us and the constructors we can use!<\/p>\n<p><strong>1. URL(String address)throws MalFormedException &#8211;<\/strong> This constructor takes in a URL and converts it to a URL object for you.<\/p>\n<p><strong>2. URL(String protocol, String host, String file) &#8211;<\/strong> This constructor takes in the protocol, the hostname, and the file that we are trying to reach and converts it to a URL object.<\/p>\n<p><strong>3. URL(String protocol, String host, int port, String file) &#8211;<\/strong> This constructor is similar to the previous one. The only additional parameter it takes into account is the port number. You can specify any port number here. This will make a URL object based on the passed parameters.<\/p>\n<p><strong>3. URL(String protocol, String host, int port, String file, URLStreamHandler handler) &#8211;<\/strong> This allows you to specify a handler along with the host, port, and the file name.<\/p>\n<p><strong>4. URL(URL context, String spec, URLStreamHandler handler) &#8211;<\/strong> This constructor returns a URL object by parsing the spec with the given handler.<\/p>\n<h3>Methods in the Java URL Class<\/h3>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Methods-in-the-URL-Class.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-85701\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Methods-in-the-URL-Class.jpg\" alt=\"Methods in Java URL Class\" width=\"1200\" height=\"628\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Methods-in-the-URL-Class.jpg 1200w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Methods-in-the-URL-Class-300x157.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Methods-in-the-URL-Class-1024x536.jpg 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Methods-in-the-URL-Class-150x79.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Methods-in-the-URL-Class-768x402.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Methods-in-the-URL-Class-720x377.jpg 720w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Methods-in-the-URL-Class-520x272.jpg 520w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Methods-in-the-URL-Class-320x167.jpg 320w\" sizes=\"auto, (max-width: 1200px) 100vw, 1200px\" \/><\/a><\/p>\n<p>There are a few methods that we need to learn about before we progress into the programming part.<\/p>\n<ul>\n<li><strong>public String toString() &#8211;<\/strong> This converts the URL to a string object and returns it. Essential for performing string manipulations on it.<\/li>\n<li><strong>public String getAuthority() &#8211;<\/strong> This returns the authority of the URL. This is basically a collection of the hostname and the port.<\/li>\n<li><strong>public String getPath() &#8211;<\/strong> This method returns the URL as a String.<\/li>\n<li><strong>public String getQuery() &#8211;<\/strong> The query of a URL is the request for a certain type of data in the database. It can also be a specific file in the website directory or a search query.<\/li>\n<li><strong>public String getHost() &#8211;<\/strong> This returns an IPV6 format of the hostname in the URL.<\/li>\n<li><strong>public String getFile() &#8211;<\/strong> This method is useful for returning the filename of the resource we are requesting.<\/li>\n<li><strong>public int getPort() &#8211;<\/strong> This method returns the port coupled with the protocol in the URL. Returns -1 if no value is found.<\/li>\n<li><strong>public int getDefaultPort() &#8211;<\/strong> This method is useful for returning the default port value.<\/li>\n<li><strong>public String getProtocol() &#8211;<\/strong> This method is useful for returning the protocol of the URL.<\/li>\n<li><strong>public URI toURI() &#8211;<\/strong> This method returns a URI of the specified URL.<\/li>\n<li><strong>public String getref() &#8211;<\/strong> This method is useful for returning the anchor or the reference of the particular URL.<\/li>\n<li><strong>public URLConnection OpenConnection() &#8211;<\/strong> This function returns an instance of the URLConnection, connected with the particular URL.<\/li>\n<li><strong>public Object getContent() &#8211;<\/strong> This method is useful for returning the content of the URL. This is returned as an Object.<\/li>\n<\/ul>\n<p>All the methods that return String return null when no value is found. All the methods that return in \u2018int; return -1 when no value can be parsed through the URL.<\/p>\n<p>Enough theory! Let us code an example and see how it looks.<\/p>\n<p><strong>Java program to illustrate the methods of the URL class:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.dataflair.javaurl;\r\nimport java.net.*;\r\npublic class TestURL\r\n{\r\n    public static void main(String[] args)throws Exception{\r\n        String url=\"https:\/\/data-flair.training\/blogs\/java-tutorial\/\";\r\n\r\n\r\n        URL testurl= new URL(url);\r\n        System.out.println(\"The string representation of the URL -&gt; \"+testurl.toString());\r\n        System.out.println(\"The Authority of the URL -&gt; \"+testurl.getAuthority());\r\n        System.out.println(\"The Path of the URL -&gt; \"+testurl.getPath());\r\n        System.out.println(\"The Query of the URL -&gt; \"+testurl.getQuery());\r\n        System.out.println(\"The host of the URL -&gt; \"+testurl.getHost());\r\n        System.out.println(\"The file of the URL -&gt; \"+testurl.getFile());\r\n        System.out.println(\"The port of the URL -&gt; \"+testurl.getPort());\r\n        System.out.println(\"The default port of the URL -&gt; \"+testurl.getDefaultPort());\r\n        System.out.println(\"The protocol of the URL -&gt; \"+testurl.getProtocol());\r\n        \r\n        \r\n        System.out.println(\"The results are null or -1 in some cases because no particular values could not be parsed\");\r\n\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">The string representation of the URL -&gt; https:\/\/data-flair.training\/blogs\/java-tutorial\/<br \/>\nThe Authority of the URL -&gt; data-flair.training<br \/>\nThe Path of the URL -&gt; \/blogs\/java-tutorial\/<br \/>\nThe Query of the URL -&gt; null<br \/>\nThe host of the URL -&gt; data-flair.training<br \/>\nThe file of the URL -&gt; \/blogs\/java-tutorial\/<br \/>\nThe port of the URL -&gt; -1<br \/>\nThe default port of the URL -&gt; 443<br \/>\nThe protocol of the URL -&gt; https<br \/>\nThe results are null or -1 in some cases because no particular values could not be parsed<\/div>\n<h3>Summary<\/h3>\n<p>We have reached the end of another interesting article. We learned about the different methods that the URL class in Java provides us.<\/p>\n<p>More complex URLs are easily parsable by these methods. In Networking applications, a programmer needs to use these methods.<\/p>\n<p>Can you imagine the inconvenience we would have faced if there weren\u2019t any inbuilt URL parsing methods in Java? We had to hard-code every method from the ground up. That would lead to confusion and errors.<\/p>\n<p>That is exactly why the URL class is a favourite for almost every Java Developer out there.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In programming, we frequently need to work with URLs. But what are URLs anyway? Sounds complex. The full form of URL is Uniform Resource Locator. So from the full form, we can understand that&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":85700,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[6364,7734,7735,12697,15183],"class_list":["post-12711","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-how-to-use-java-8-url-class","tag-java-url-class-example","tag-java-url-class-with-examples","tag-segments-of-a-url","tag-url-class-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Learn Java URL Class With Examples - DataFlair<\/title>\n<meta name=\"description\" content=\"Java URL Class-What is Uniform Resource Locator,Segments of a URL,Constructors for Java URL Class,Java URL Class Example,how to use URL Class in Java\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/java-url-class\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Learn Java URL Class With Examples - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Java URL Class-What is Uniform Resource Locator,Segments of a URL,Constructors for Java URL Class,Java URL Class Example,how to use URL Class in Java\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/java-url-class\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2018-04-07T17:42:21+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-05-28T10:35:26+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Java-URL-Class.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Learn Java URL Class With Examples - DataFlair","description":"Java URL Class-What is Uniform Resource Locator,Segments of a URL,Constructors for Java URL Class,Java URL Class Example,how to use URL Class in Java","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/java-url-class\/","og_locale":"en_US","og_type":"article","og_title":"Learn Java URL Class With Examples - DataFlair","og_description":"Java URL Class-What is Uniform Resource Locator,Segments of a URL,Constructors for Java URL Class,Java URL Class Example,how to use URL Class in Java","og_url":"https:\/\/data-flair.training\/blogs\/java-url-class\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2018-04-07T17:42:21+00:00","article_modified_time":"2026-05-28T10:35:26+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Java-URL-Class.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/java-url-class\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/java-url-class\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"Learn Java URL Class With Examples","datePublished":"2018-04-07T17:42:21+00:00","dateModified":"2026-05-28T10:35:26+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-url-class\/"},"wordCount":1125,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-url-class\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Java-URL-Class.jpg","keywords":["How to use Java 8 URL CLass","Java URL Class Example","Java URL Class With Examples","Segments of a URL","URL Class in Java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/java-url-class\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/java-url-class\/","url":"https:\/\/data-flair.training\/blogs\/java-url-class\/","name":"Learn Java URL Class With Examples - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-url-class\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-url-class\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Java-URL-Class.jpg","datePublished":"2018-04-07T17:42:21+00:00","dateModified":"2026-05-28T10:35:26+00:00","description":"Java URL Class-What is Uniform Resource Locator,Segments of a URL,Constructors for Java URL Class,Java URL Class Example,how to use URL Class in Java","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/java-url-class\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/java-url-class\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/java-url-class\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Java-URL-Class.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Java-URL-Class.jpg","width":1200,"height":628,"caption":"Java URL Class"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/java-url-class\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Java Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/java\/"},{"@type":"ListItem","position":3,"name":"Learn Java URL Class With Examples"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/12711","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=12711"}],"version-history":[{"count":9,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/12711\/revisions"}],"predecessor-version":[{"id":148477,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/12711\/revisions\/148477"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/85700"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=12711"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=12711"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=12711"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}