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
URLclass is present in thejava.netpackage.
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 numberint 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
URLobject.
URL url= new URL("https:// www.educative.io:8000");
- In line number 8, we use the
getPortmethod to get the port number of theURLobject.
int portNumber =url.getPort();
- In lines 9 and 10, we print the
URLand the port number of theURL.