Home » Core Java » net » URL » Parse URL example

About Ilias Tsagklis

Avatar photo
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Parse URL example

In this example we shall show you how to parse a URL. Class URL represents a Uniform Resource Locator, a pointer to a “resource” on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine. To parse a URL one should perform the following steps:

  • Create a URL object from the String representation. 
  • Use getProtocol() API method to get the protocol name of this URL, that is HTTP protocol.
  • Use getHost() API method to get the host name of this URL, if applicable.
  • Use getPort() API method to get the port number of this URL. 
  • Use getPath() API method to get the path part of this URL,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.net.MalformedURLException;
import java.net.URL;

public class ParseURLExample {
	public static void main(String[] args) {
		// Create a URL
		try {
			URL url = new URL("http://www.javacodegeeks.com:80/");
			String protocol = url.getProtocol();
		    String host = url.getHost();
		    int port = url.getPort();
		    String path = url.getPath();
		    System.out.println("URL created: " + url);
		    System.out.println("protocol: " + protocol);
		    System.out.println("host: " + host);
		    System.out.println("port: " + port);
		    System.out.println("path: " + path);
		catch (MalformedURLException e) {
			System.out.println("Malformed URL: " + e.getMessage());



URL created: http://www.javacodegeeks.com:80/
protocol: http
host: www.javacodegeeks.com
port: 80
path: /

This was an example of how to parse a URL in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments