URL class

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java URL

The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide Web. For example:

  1. http://www.tutorialtours.com/java-tutorial  

A URL contains much information:

  1. Protocol: In this case, http is the protocol.
  2. Server name or IP Address: In this case, www.javatpoint.com is the server name.
  3. Port Number: It is an optional attribute. If we write http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is not mentioned in the URL, it returns -1.
  4. File Name or directory name: In this case, index.jsp is the file name.

Commonly used methods of Java URL class

The java.net.URL class provides many methods. The important methods of URL class are given below.



public String getProtocol()

it returns the protocol of the URL.

public String getHost()

it returns the host name of the URL.

public String getPort()

it returns the Port Number of the URL.

public String getFile()

it returns the file name of the URL.

public URLConnection openConnection()

it returns the instance of URLConnection i.e. associated with this URL.

Example of Java URL class

  1. //URLDemo.java  
  2. import java.io.*;  
  3. import java.net.*;  
  4. public class URLDemo{  
  5. public static void main(String[] args){  
  6. try{  
  7. URL url=new URL("http://www.javatpoint.com/java-tutorial");  
  9. System.out.println("Protocol: "+url.getProtocol());  
  10. System.out.println("Host Name: "+url.getHost());  
  11. System.out.println("Port Number: "+url.getPort());  
  12. System.out.println("File Name: "+url.getFile());  
  14. }catch(Exception e){System.out.println(e);}  
  15. }  
  16. }  


       Protocol: http
       Host Name: www.tutorialtours.com
       Port Number: -1
       File Name: /java-tutorial