Last Updated : 11 Jul, 2025
The
getPort()function is a part of
URL class. The function getPort() returns the port of a specified URL. The function returns the port number or -1 if the port is not set
Function Signaturepublic int getPort()Syntax
url.getPort()Return Type
: The function returns
IntegerType
Parameter: This function does not require any parameter Below programs illustrates the use of getPort() function:
Example 1display port of specified URL
Java
// Java program to show the use of the function getPort()
import java.net.*;
class Solution {
public static void main(String args[])
{
// url object
URL url = null;
try {
// create a URL
url = new URL("https:// www.geeksforgeeks.org:80");
// get the port
int _port = url.getPort();
// display the URL
System.out.println("URL = " + url);
// display the port
System.out.println(" Port=" + _port);
}
// if any error occurs
catch (Exception e) {
// display the error
System.out.println(e);
}
}
}
Output:
URL = https:// www.geeksforgeeks.org:80 Port=80Example 2:
Create a URL with no defined port and then try to get the port using the getPort() function.
Java
// Java program to show the
// use of the function getPort()
import java.net.*;
class Solution {
public static void main(String args[])
{
// url object
URL url = null;
try {
// create a URL
url = new URL("https:// www.geeksforgeeks.org");
// get the port
int _port = url.getPort();
// display the URL
System.out.println("URL = " + url);
// display the port
System.out.println(" Port=" + _port);
}
// if any error occurs
catch (Exception e) {
// display the error
System.out.println(e);
}
}
}
Output:
URL = https:// www.geeksforgeeks.org Port=-1
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4