~/ learn/ comp-348/ cards/ The URL class: construct, split, read
1 of 5

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

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/de1f3823-7c7b-4f21-ad67-17a37fd304ce/flashcard utf-8 LF