Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

What is the difference between java.net.URL and java.net.URI? Why is URL.equals considered dangerous, and what changed for URL constructors in recent JDKs?

java.net.URI is a parser for identifiers: it splits a string into scheme, host, path, query and fragment, compares them as text, and can resolve, relativize and normalize them, all without touching the network. java.net.URL is a locator tied to a protocol handler that can open a connection, and its equals() and hashCode() may look up host names in DNS, which makes them slow and network-dependent. Since Java 20 the URL constructors are deprecated, and we create a URL with URI.create(...).toURL() instead.

Why this question is asked

Almost every service we write handles addresses: endpoints in configuration, links in responses, callback addresses from partners. Java has two classes for them, and picking the wrong one causes surprisingly real problems, from a HashSet that blocks on DNS to two different sites being treated as the same key. Interviewers ask this question to see whether we know what each class is for and whether we have kept up with the deprecation in recent JDKs. In this answer, we will recap what each class represents, look at how URL.equals really works and why it is dangerous, see what changed in Java 20, and finish with the parsing operations that only URI offers.

1A Quick Recap: Identifier Versus Locator

A URI, a Uniform Resource Identifier, is a string that names something, following the syntax of the URI standard: a scheme such as https, then an authority with host and port, a path, an optional query after a question mark, and an optional fragment after a hash sign. java.net.URI is a parser and a value object for exactly that syntax. It checks the string, gives us the parts, and compares URIs component by component. It never opens a connection and never looks anything up.

A URL, a Uniform Resource Locator, is a URI that also tells us how to reach the resource. java.net.URL goes one step further than the syntax: when we create one, Java looks for a protocol handler (a URLStreamHandler) for the scheme, and the URL object keeps that handler so it can later call openConnection() or openStream(). That is why new URL("foo://x") fails with MalformedURLException: unknown protocol: foo, while URI.create("foo://x") is perfectly happy. A URI with an unknown scheme is still a valid identifier; it simply cannot be a URL in this JVM.

Java
URI id = URI.create("foo://example/a/b"); // fine: just syntax
System.out.println(id.getScheme()); // foo
System.out.println(id.getPath()); // /a/b
URL loc = URI.create("https://example.com/a").toURL(); // has an https handler
InputStream in = loc.openStream(); // a URL can fetch; a URI cannot
URI and URL side by side
Questionjava.net.URIjava.net.URL
What is it?A parsed identifierA locator with a protocol handler
Unknown scheme such as foo:AcceptedMalformedURLException
Can it open a connection?NoYes, openConnection() and openStream()
How does equals() compare hosts?As text, case-insensitiveMay resolve both hosts through DNS
resolve, relativize, normalizeYesNo
Constructors in Java 20 and laterNormalDeprecated; use URI.toURL()

So URI is about what the string means, and URL is about how to fetch it. We keep URI as the value we store and compare, and convert to a URL only when an old API needs one.

2How URL.equals Really Compares Two URLs

The surprise is in the equality rules. URL.equals() delegates to its protocol handler, and the handler compares the protocol, port, file and fragment as we would expect, but for the host it does something unusual: it resolves both host names to IP addresses and treats the hosts as equal if the addresses match. Only if a name cannot be resolved does it fall back to comparing the names as text. URL.hashCode() also resolves the host, so that equal URLs get equal hash codes.

Java
URL a = URI.create("http://shop.example.com/").toURL();
URL b = URI.create("http://blog.example.com/").toURL();
// Both names point to the same shared web server, 203.0.113.10
System.out.println(a.equals(b)); // true: blocks on two DNS lookups, then compares IPs
URI x = URI.create("http://shop.example.com/");
URI y = URI.create("http://blog.example.com/");
System.out.println(x.equals(y)); // false: compared as text, no network

Notice the three separate problems this creates. First, it is slow: a DNS lookup can take milliseconds, or seconds if the resolver is struggling, and it happens inside a method we expect to be instant. Second, it is wrong for virtual hosting: two completely different sites served from one IP address are reported as equal. Third, the answer depends on the network: the same two URLs can be equal on a laptop connected to the office VPN and unequal in a container that resolves names differently, or when DNS is briefly down and the comparison falls back to text.

3Why URL Must Never Be a Map Key or a Set Element

A HashSet or HashMap calls hashCode() on every insert and lookup, and equals() whenever two hashes match. With URL as the element type, every add() and contains() can trigger DNS lookups. A crawler that stores visited pages in a Set<URL> ends up doing a network round trip for each check, and two pages on different virtual hosts can collapse into one entry and be silently skipped.

Java
Set<URL> seen = new HashSet<>();
seen.add(URI.create("http://shop.example.com/").toURL()); // DNS lookup in hashCode()
seen.contains(URI.create("http://blog.example.com/").toURL()); // true, wrong page reported as seen
Set<URI> seenFixed = new HashSet<>();
seenFixed.add(URI.create("http://shop.example.com/")); // no network
seenFixed.contains(URI.create("http://blog.example.com/")); // false, as expected

The fix is simply to use URI as the key type. URI.equals() compares the components as text, with the scheme and host compared case-insensitively, so it is fast, stable and the same on every machine.

4What Changed for URL Constructors in Java 20

Because URL parsing is lenient and inconsistent with the URI standard, and because people kept building URLs from raw strings, Java 20 deprecated all public URL constructors. They still work, but the compiler now warns, and the recommended route is to parse with URI first and convert.

Java
// Before (deprecated since Java 20, compiler warning)
URL old = new URL("https://api.example.com/orders?id=7");
// After
URL url = URI.create("https://api.example.com/orders?id=7").toURL();
URI.create("orders?id=7").toURL(); // IllegalArgumentException: URI is not absolute
URI.create("https://a b/"); // IllegalArgumentException: Illegal character in authority

The reason for going through URI is that URI validates the syntax strictly, so a malformed string fails early with a clear message instead of producing a URL that behaves oddly later. Notice that toURL() requires an absolute URI, one with a scheme, and that URI.create throws an unchecked IllegalArgumentException, while the URI constructor throws the checked URISyntaxException, which is the better choice when the string comes from a user and we want to handle the error.

5Working With Paths: resolve, relativize and normalize

URI also gives us the operations we need when we combine and clean up addresses, which URL simply does not have. resolve() builds a full address from a base and a relative reference, exactly as a browser does with a link on a page. relativize() does the opposite. normalize() removes . and .. segments.

Java
URI base = URI.create("https://example.com/docs/guide/");
System.out.println(base.resolve("intro.html")); // https://example.com/docs/guide/intro.html
System.out.println(base.resolve("../api/v1")); // https://example.com/docs/api/v1
System.out.println(base.resolve("/status")); // https://example.com/status
URI messy = URI.create("https://example.com/a/./b/../c");
System.out.println(messy.normalize()); // https://example.com/a/c
URI full = URI.create("https://example.com/docs/guide/intro.html");
System.out.println(base.relativize(full)); // intro.html

But there is a catch with resolve(): the trailing slash on the base matters. Resolving "intro.html" against https://example.com/docs/guide without the slash replaces the last segment and gives https://example.com/docs/intro.html. This is standard URI behaviour, and a common reason a client calls the wrong endpoint.

6Follow-up questions

Is URL ever the right type to keep in a field?

Rarely. It is reasonable at the boundary with an old API that only accepts URL, such as some class loader or resource methods, but the value we store, compare and pass around should be a URI. We convert with toURL() at the last moment, so the DNS-dependent equality never reaches our collections.

Does URI.equals ignore case everywhere?

No. The scheme and the host are compared without regard to case, because the standard says they are case-insensitive. The path, query and fragment are compared exactly, and percent-encoded octets are compared without regard to the case of their hex digits. So https://EXAMPLE.com/a equals https://example.com/a, but https://example.com/A does not.

7Conclusion

In this answer, we saw that URI is a syntax parser and value object, while URL is a locator bound to a protocol handler that can open connections. URL.equals() and hashCode() resolve host names through DNS, which makes them slow, wrong for virtual hosts and dependent on the network, so URL must never be a set element or map key. Since Java 20 the URL constructors are deprecated in favour of URI.create(...).toURL(), and URI is also where resolve, relativize and normalize live.

What to say in the interviewAbout 80 seconds aloud

Open with

URI and URL look similar but do different jobs. java.net.URI is just a parser and value object for the URI syntax: scheme, host, path, query and fragment. It compares components as text and never touches the network, so a URI with an unknown scheme is still valid. java.net.URL is a locator: it is bound to a protocol handler and can open a connection or a stream.

Then, if they want more

The dangerous part is URL.equals and hashCode. For the host they resolve both names through DNS and compare IP addresses, so they can block on a network call, they treat two virtual hosts on the same IP as equal, and the result can change depending on the network the code runs in.

That is why I never put URL in a HashSet or use it as a map key; I use URI instead.

In Java 20 all URL constructors were deprecated, because URL parsing was lenient and inconsistent, so now I write URI.create of the string and then toURL, or use the URI constructor when I want a checked exception for user input.

URI also gives me resolve, relativize and normalize, which I use to build endpoints from a base address, keeping in mind that the trailing slash on the base changes how relative paths resolve.

About this answer

Last updated
12 November 2026
Versions it names
Java 20
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is the difference between java.net.URL and java.net.URI? Why is URL.equals...": https://scrivio-interview-library.netlify.app/java/networking/0f322fa64c/