Why am I getting the port number -1 when I use the getPort() method of URL?

Tim Rohaly

A URL doesn't imply a socket connection to a resource - it is just a string representation telling you where that resource can be found on the network. In particular, in order to determine the "port", the URL class simply parses the URL string that you specified in the constructor. Since the "port" field of a URL is optional, getPort() returns -1 in the case where the port was not explicitly specified. For example, this code:

URL url = new URL("http://www.jguru.com/");
System.out.println("Port = " + url.getPort());
will print "Port = -1" because there is no port specified in the given URL (you can assume it uses the default port number for that protocol). However, this other code:
URL url = new URL("http://www.jguru.com:80/");
System.out.println("Port = " + url.getPort());
will print "Port = 80" because the port was explicit in the URL.