Java URI Class

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 203 of 306

The Java URI class (java.net.URI) represents a Uniform Resource Identifier: a string that names or locates a resource, such as https://example.com/docs, mailto:info@example.com or urn:isbn:9780134685991. URI parses and checks the address strictly, and it never touches the network.

You use URI to validate addresses, read their parts, join relative links to a base address, and build URLs safely. It is also what HttpClient and the Path API expect, and the recommended way to create a URL.


URI vs URL vs URN

These three terms are often mixed up. A URI is the general idea; a URL and a URN are two kinds of URI.

TermMeaningExample
URIAny identifier for a resourceAll examples below
URLA URI that says where a resource is and how to get ithttps://example.com/report.pdf
URNA URI that gives a resource a permanent nameurn:isbn:9780134685991

In Java, the two classes have different jobs:

java.net.URIjava.net.URL
PurposeParse, check, compare and combine identifiersOpen a connection and read a resource
Relative addressesSupported (../images/logo.png)Not supported
Network accessNeveropenStream(), openConnection()
equals()Pure text comparisonMay do a DNS lookup
Converturi.toURL()url.toURI()

Note: A good rule: keep addresses as URI objects in your program, and convert to URL only when you need to open a connection. The Java URL class lesson covers the URL side.


How to Create a URI in Java

There are three ways to create a URI.

WayInvalid inputUse it when
URI.create(String)Throws unchecked IllegalArgumentExceptionThe address is fixed in your code
new URI(String)Throws checked URISyntaxExceptionThe address comes from users or files
new URI(scheme, userInfo, host, port, path, query, fragment)Encodes illegal characters for youYou build an address from separate parts
import java.net.URI;
import java.net.URISyntaxException;

public class CreateUri {
    public static void main(String[] args) {
        // 1. URI.create: short, for addresses you know are valid
        URI home = URI.create("https://gocourse.example.com/java/");
        System.out.println("create(): " + home);

        // 2. new URI(String): forces you to handle bad input
        String userInput = "https://example.com/my report.pdf";
        try {
            URI fromUser = new URI(userInput);
            System.out.println("Parsed: " + fromUser);
        } catch (URISyntaxException e) {
            System.out.println("Invalid: " + e.getReason() + " at index " + e.getIndex());
        }

        // 3. Multi-argument constructor: encodes the space for you
        try {
            URI built = new URI("https", "example.com", "/my report.pdf", null);
            System.out.println("Built : " + built);
        } catch (URISyntaxException e) {
            System.out.println("Unexpected: " + e.getMessage());
        }
    }
}

Output:

create(): https://gocourse.example.com/java/
Invalid: Illegal character in path at index 22
Built : https://example.com/my%20report.pdf

How it works:

  • URI.create() is a shortcut for new URI(...) that wraps the checked exception in an IllegalArgumentException.
  • The space in my report.pdf is illegal in a URI. new URI(String) throws URISyntaxException, whose getReason() and getIndex() say what is wrong and where.
  • The constructor new URI(scheme, host, path, fragment) treats each argument as plain text and percent-encodes illegal characters, so the space becomes %20.

Getting URI Parts with the Java URI Class

URI has a getter for every component. Missing parts return null, and a missing port returns -1.

import java.net.URI;

public class UriParts {
    public static void main(String[] args) {
        URI uri = URI.create("https://ravi@api.example.com:8443/v1/orders/42?status=paid&sort=date#items");

        System.out.println("Scheme   : " + uri.getScheme());
        System.out.println("UserInfo : " + uri.getUserInfo());
        System.out.println("Host     : " + uri.getHost());
        System.out.println("Port     : " + uri.getPort());
        System.out.println("Authority: " + uri.getAuthority());
        System.out.println("Path     : " + uri.getPath());
        System.out.println("Query    : " + uri.getQuery());
        System.out.println("Fragment : " + uri.getFragment());
        System.out.println("Absolute : " + uri.isAbsolute());

        URI relative = URI.create("images/logo.png");
        System.out.println("Relative scheme: " + relative.getScheme()
                + ", host: " + relative.getHost() + ", port: " + relative.getPort()
                + ", absolute: " + relative.isAbsolute());
    }
}

Output:

Scheme   : https
UserInfo : ravi
Host     : api.example.com
Port     : 8443
Authority: ravi@api.example.com:8443
Path     : /v1/orders/42
Query    : status=paid&sort=date
Fragment : items
Absolute : true
Relative scheme: null, host: null, port: -1, absolute: false

How it works:

  • A URI is absolute when it has a scheme (https). images/logo.png has none, so it is relative and its scheme, host and port are empty.
  • Unlike URL, URI happily stores relative addresses; you combine them with a base later using resolve().

Decoded vs Raw Getters

Each text getter has a raw twin. The normal getter decodes %xx sequences; the raw getter returns the text exactly as written.

import java.net.URI;

public class RawGetters {
    public static void main(String[] args) {
        URI uri = URI.create("https://example.com/files/annual%20report%202025.pdf?title=Q1%20%26%20Q2");

        System.out.println("getPath()     : " + uri.getPath());
        System.out.println("getRawPath()  : " + uri.getRawPath());
        System.out.println("getQuery()    : " + uri.getQuery());
        System.out.println("getRawQuery() : " + uri.getRawQuery());
    }
}

Output:

getPath()     : /files/annual report 2025.pdf
getRawPath()  : /files/annual%20report%202025.pdf
getQuery()    : title=Q1 & Q2
getRawQuery() : title=Q1%20%26%20Q2

How it works:

  • getPath() decodes %20 to a space, which is handy for showing a file name to a user.
  • getQuery() decodes %26 to &. That makes title=Q1 & Q2 look like two parameters, so when you split a query into parameters, always split the raw query first and decode each value afterwards.

Hierarchical and Opaque URIs

Most URIs are hierarchical: after the scheme they have //, an authority and a path, like web addresses. Some are opaque: the part after the scheme has no inner structure, like email links and URNs.

import java.net.URI;

public class OpaqueUris {
    public static void main(String[] args) {
        URI[] uris = {
                URI.create("https://example.com/contact"),
                URI.create("mailto:support@example.com"),
                URI.create("urn:isbn:9780134685991"),
                URI.create("tel:+91-44-1234-5678")
        };

        for (URI uri : uris) {
            System.out.printf("%-30s opaque=%-5s scheme=%-6s ssp=%s%n",
                    uri, uri.isOpaque(), uri.getScheme(), uri.getSchemeSpecificPart());
        }
    }
}

Output:

https://example.com/contact    opaque=false scheme=https  ssp=//example.com/contact
mailto:support@example.com     opaque=true  scheme=mailto ssp=support@example.com
urn:isbn:9780134685991         opaque=true  scheme=urn    ssp=isbn:9780134685991
tel:+91-44-1234-5678           opaque=true  scheme=tel    ssp=+91-44-1234-5678

How it works:

  • getSchemeSpecificPart() returns everything between the scheme and the fragment.
  • For opaque URIs, getHost() and getPath() return null, because the text after the scheme is not split into parts. Read the scheme-specific part instead.

Web pages are full of relative links like ../css/style.css. resolve() combines a base URI with a relative one, exactly as a browser does.

import java.net.URI;

public class ResolveDemo {
    public static void main(String[] args) {
        URI page = URI.create("https://gocourse.example.com/java/networking/uri-class.html");

        String[] links = {
                "url-class.html",          // same folder
                "../threads/intro.html",   // one folder up
                "/about",                  // from the site root
                "?page=2",                 // same page, new query
                "#examples",               // same page, a section
                "https://dev.java/learn/"  // already absolute
        };

        for (String link : links) {
            System.out.printf("%-24s -> %s%n", link, page.resolve(link));
        }
    }
}

Output:

url-class.html           -> https://gocourse.example.com/java/networking/url-class.html
../threads/intro.html    -> https://gocourse.example.com/java/threads/intro.html
/about                   -> https://gocourse.example.com/about
?page=2                  -> https://gocourse.example.com/java/networking/?page=2
#examples                -> https://gocourse.example.com/java/networking/uri-class.html#examples
https://dev.java/learn/  -> https://dev.java/learn/

How it works:

  • A relative path replaces the last segment of the base path (uri-class.html), so url-class.html lands in the same folder.
  • .. moves one folder up, and a path starting with / starts again from the site root.
  • An absolute link is returned unchanged.
  • Java's resolve() follows the older RFC 2396 rules, so a query-only link (?page=2) drops the file name. Browsers keep it (uri-class.html?page=2); if that matters, add the query to the full path yourself.

Note: The base matters: https://site.com/docs (no trailing slash) treats docs as a file, while https://site.com/docs/ treats it as a folder. Resolving intro.html gives /intro.html and /docs/intro.html respectively.


Cleaning and Comparing URIs: normalize(), relativize(), equals()

MethodWhat it does
normalize()Removes . and .. segments from the path
relativize(other)The reverse of resolve(): the relative path from this URI to other
equals(other)Compares two URIs; scheme and host are compared without case
compareTo(other)Orders URIs, so they can be sorted
import java.net.URI;
import java.util.List;
import java.util.TreeSet;

public class NormalizeCompare {
    public static void main(String[] args) {
        URI messy = URI.create("https://example.com/docs/./guide/../api/index.html");
        System.out.println("normalize : " + messy.normalize());

        URI base = URI.create("https://example.com/docs/");
        URI page = URI.create("https://example.com/docs/api/index.html");
        System.out.println("relativize: " + base.relativize(page));

        URI upper = URI.create("HTTPS://Example.COM/Docs");
        URI lower = URI.create("https://example.com/Docs");
        URI otherPath = URI.create("https://example.com/docs");
        System.out.println("scheme/host case ignored: " + upper.equals(lower));
        System.out.println("path case matters       : " + lower.equals(otherPath));

        // URIs are Comparable, so a TreeSet keeps them sorted and unique
        TreeSet<URI> sitemap = new TreeSet<>(List.of(
                URI.create("https://example.com/contact"),
                URI.create("https://example.com/about"),
                URI.create("https://example.com/blog/java"),
                URI.create("https://example.com/about")));
        System.out.println("sitemap   : " + sitemap);
    }
}

Output:

normalize : https://example.com/docs/api/index.html
relativize: api/index.html
scheme/host case ignored: true
path case matters       : false
sitemap   : [https://example.com/about, https://example.com/blog/java, https://example.com/contact]

How it works:

  • normalize() removes ./ and cancels guide/.., leaving the shortest equivalent path. Normalize addresses before comparing or storing them.
  • relativize() returns api/index.html, and base.resolve("api/index.html") would give the full address back.
  • Scheme and host names are case-insensitive on the web, so URI.equals() ignores their case. Paths can be case-sensitive, so /Docs and /docs are different.
  • Because URI implements Comparable, a TreeSet sorts the addresses and drops the duplicate /about.

Converting Between URI, URL and Path

URI is the bridge between the networking and file APIs.

import java.net.URI;
import java.net.URL;
import java.nio.file.Path;

public class ConvertUri {
    public static void main(String[] args) throws Exception {
        // URI <-> URL
        URI apiUri = URI.create("https://api.example.com/v1/users");
        URL apiUrl = apiUri.toURL();
        URI backToUri = apiUrl.toURI();
        System.out.println("URL : " + apiUrl.getHost() + apiUrl.getPath());
        System.out.println("Same after round trip: " + apiUri.equals(backToUri));

        // Path <-> URI (file: scheme)
        Path report = Path.of("/home/asha/reports/sales 2025.csv");
        URI fileUri = report.toUri();
        System.out.println("file URI : " + fileUri);
        System.out.println("back to Path: " + Path.of(fileUri));

        // Non-ASCII characters: toASCIIString() percent-encodes them
        URI tamil = new URI("https", "example.com", "/வணக்கம்", null);
        System.out.println("toString      : " + tamil);
        System.out.println("toASCIIString : " + tamil.toASCIIString());
    }
}

Output:

URL : api.example.com/v1/users
Same after round trip: true
file URI : file:///home/asha/reports/sales%202025.csv
back to Path: /home/asha/reports/sales 2025.csv
toString      : https://example.com/வணக்கம்
toASCIIString : https://example.com/%E0%AE%B5%E0%AE%A3%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%AE%E0%AF%8D

How it works:

  • toURL() and toURI() convert in both directions without losing information.
  • Path.toUri() builds a file: URI and encodes the space; Path.of(URI) turns it back into a path. On Windows the URI looks like file:///C:/Users/....
  • toString() keeps non-ASCII characters as they are. toASCIIString() encodes them as UTF-8 bytes in %xx form, which is what you must send over HTTP.

Real-World Example: A Safe API URL Builder

Apps that call REST APIs build many URLs from a base address, path segments and query parameters. Gluing strings together breaks as soon as a value contains a space, / or &. This small builder encodes every piece correctly and returns a URI ready for HttpClient. It also parses a query string back into a map.

import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ApiUrlBuilder {
    private final URI baseUri;
    private final List<String> pathSegments = new ArrayList<>();
    private final Map<String, String> queryParams = new LinkedHashMap<>();

    private ApiUrlBuilder(String base) {
        this.baseUri = URI.create(base.endsWith("/") ? base : base + "/");
    }

    static ApiUrlBuilder from(String base) {
        return new ApiUrlBuilder(base);
    }

    ApiUrlBuilder path(Object segment) {
        pathSegments.add(encode(segment.toString()).replace("+", "%20")); // spaces in paths are %20
        return this;
    }

    ApiUrlBuilder query(String name, Object value) {
        queryParams.put(encode(name), encode(value.toString()));
        return this;
    }

    URI build() {
        StringBuilder relative = new StringBuilder(String.join("/", pathSegments));
        if (!queryParams.isEmpty()) {
            relative.append('?');
            queryParams.forEach((name, value) -> relative.append(name).append('=').append(value).append('&'));
            relative.setLength(relative.length() - 1);               // remove the last &
        }
        return baseUri.resolve(relative.toString());
    }

    static Map<String, String> parseQuery(URI uri) {
        Map<String, String> params = new LinkedHashMap<>();
        if (uri.getRawQuery() == null) return params;
        for (String pair : uri.getRawQuery().split("&")) {               // split the RAW query
            String[] parts = pair.split("=", 2);
            params.put(decode(parts[0]), parts.length > 1 ? decode(parts[1]) : "");
        }
        return params;
    }

    private static String encode(String text) {
        return URLEncoder.encode(text, StandardCharsets.UTF_8);
    }

    private static String decode(String text) {
        return URLDecoder.decode(text, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        URI search = ApiUrlBuilder.from("https://api.shop.example.com/v2")
                .path("stores").path("Chennai Central").path("products")
                .query("q", "laptop & bag")
                .query("maxPrice", 55000)
                .query("sort", "price/asc")
                .build();

        System.out.println(search);
        System.out.println("Host : " + search.getHost());
        System.out.println("Path : " + search.getPath());
        parseQuery(search).forEach((name, value) -> System.out.println("  " + name + " = " + value));

        URI order = ApiUrlBuilder.from("https://api.shop.example.com/v2/").path("orders").path(1042).build();
        System.out.println(order);
    }
}

Output:

https://api.shop.example.com/v2/stores/Chennai%20Central/products?q=laptop+%26+bag&maxPrice=55000&sort=price%2Fasc
Host : api.shop.example.com
Path : /v2/stores/Chennai Central/products
  q = laptop & bag
  maxPrice = 55000
  sort = price/asc
https://api.shop.example.com/v2/orders/1042

How it works:

  1. A folder-style base. The constructor makes sure the base ends with /, so resolve() adds the path under /v2/ instead of replacing v2. Both "/v2" and "/v2/" work.
  2. Encoding path segments. Each segment is encoded with URLEncoder, and + is changed to %20, because + means a space only in query strings. A / inside a segment would be encoded as %2F, so it cannot create extra folders.
  3. Encoding query parameters. Names and values are encoded separately, so & in laptop & bag becomes %26 and / in price/asc becomes %2F. A LinkedHashMap keeps the parameters in the order they were added.
  4. Building. build() joins the pieces into a relative URI and resolves it against the base, which also validates the result.
  5. Parsing back. parseQuery() splits the raw query on & and = before decoding, so encoded & characters inside values never split a parameter in two.

The URI this builder returns can be passed straight to HttpRequest.newBuilder(uri), as shown in the Java HttpClient lesson and in Java networking basics.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java URI Class and get answers drawn from it.

Signed-in readers only.