CKTIS / Java
URL(String): creating a URL object from text
java.net.URL(String) creates a URL object from text. The constructor has been deprecated since Java 20; Java SE 21 recommends using URI and converting with toURL().
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
@Deprecated(since = "20")
public URL(String spec) throws MalformedURLExceptionjava.net.URL(String) parses the spec argument as a URL. A missing protocol, unknown protocol, null, or rejection by the protocol handler causes MalformedURLException. This checked exception must be caught or declared with throws.
The constructor has been deprecated since Java 20 but remains available in Java SE 21. In new code, construct a URI first, then call toURL(). If the input may contain URI syntax errors, use new URI(spec): the constructor reports malformed syntax with the checked exception URISyntaxException. Use URI.create(spec) only for strings already known to be syntactically valid URIs, such as the fixed string in the example. This method throws the unchecked exception IllegalArgumentException on malformed syntax. Conversion requires an absolute URI and an available protocol handler; not every URI can become a URL.
Creating the object does not establish full address validity or resource availability. Validation depends on the protocol handler implementation. URL does not automatically encode characters requiring percent-encoding.
The example compares the legacy constructor with the recommended conversion and reads address components without fetching the resource. getRef() returns the fragment without #. @SuppressWarnings("deprecation") suppresses the warning solely for this demonstration.
Examples
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
public class Main {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws MalformedURLException {
String spec = "https://example.com/docs?q=java#intro";
URL legacy = new URL(spec);
URL preferred = URI.create(spec).toURL();
System.out.println(legacy.getHost());
System.out.println(legacy.getPath());
System.out.println(preferred.getQuery());
System.out.println(preferred.getRef());
}
}Result
example.com /docs q=java intro
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.