Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the URL.getPort method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring