Split a URL from args[0] and resolve its effective port
Split a URL from args[0] and resolve its effective port
Answer
URL u = new URL(args[0]); int port = u.getPort() == -1 ? u.getDefaultPort() : u.getPort(); System.out.println(u.getProtocol() + " " + u.getHost() + ":" + port); System.out.println(u.getPath() + " q=" + u.getQuery());
getPort() reports only what the URL literally said, so -1 means "unspecified" and getDefaultPort() supplies the scheme default — the ternary is the idiom worth memorising. getQuery() prints null when there is no query, and getPath() never includes it.
Harold 4e ch5 §The URL Class; JDK javadoc java.net.URL