What is the URL.getPort method in Java?

The getPort method of the URL class can be used to get the port number of the specified URL.

Syntax

public int getPort()

This method doesn’t take any parameters. The return type of the getPort method is int. If URL does not have a port number, then getPort returns -1.

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

Parts of the url

The image above highlights details about parts of the URL.

Code

The code below demonstrates how to use the getPort method:

import java.net.URL;
class GetPortExample {
public static void main( String args[] ) {
try {
URL url= new URL("https:// www.educative.io:8000");
//Get Port number
int portNumber =url.getPort();
System.out.println("The URL is : "+url);
System.out.println("Port number is : "+portNumber);
} catch (Exception e) {
System.out.println(e);
}
}
}

Explanation

In the code above,

  • In line number 6, we create an URL object.
URL url= new URL("https:// www.educative.io:8000");
  • In line number 8, we use the getPort method to get the port number of the URL object.
int portNumber =url.getPort();
  • In lines 9 and 10, we print the URL and the port number of the URL.

Free Resources