String urlString = "https://www.example.com:8080/path/to/resource"; URL url = new URL(urlString); int port = url.getPort(); System.out.println("Port number: " + port); // Output: Port number: 8080
URL url = new URL("http://localhost"); int port = url.getPort(); if (port == -1) { port = url.getDefaultPort(); } System.out.println("Port number: " + port); // Output: Port number: 80In this example, we create a URL object with only the hostname "localhost" specified. We then call getPort() to retrieve the port number, which will return -1 since no specific port is given. We then use getDefaultPort() to set the port number to the default value for HTTP, which is port 80 in this case. The final output will be the default port number. This method belongs to the java.net package library.