What is the URL.getProtocol method in Java?

The getProtocol method of the URL class can be used to get the protocol (scheme) of the URL.

Syntax

public String getProtocol()

This method doesn’t take any arguments. The return type of this method is a string.

The URL class is present in the java.net package.

Parts of the url

In the image above, the part labeled with the scheme denotes the protocol of the URL.

Code

The code below uses the getProtocol method.

import java.net.URL;
class GetRefExample {
public static void main( String args[] ) {
try {
URL url= new URL("https://www.educative.io");
//Get Protocol
String protocol=url.getProtocol();
System.out.println("The URL is : "+url);
System.out.println("The protocol is : "+protocol);
} catch (Exception e) {
System.out.println(e);
}
}
}

Explanation

In the code above:

  • On line 6, we created a URL object.
URL url= new URL("https://www.educative.io");
  • On line 8, we used the getProtocol method to get the protocol of the URL object.
String protocol=url.getProtocol();
  • On lines 9 and 10, we printed the url and protocol of the URL.

Free Resources