Thursday, September 4, 2025
HomeLanguagesJavaURL toURI() method in Java with Examples

URL toURI() method in Java with Examples

The getURI() function of URL class converts the URL object to a URI object. Any URL which compiles with RFC 2396 can be converted to URI. URLs which are not in the specified format will generate an error if converted to URI format.

Function Signature

public URI toURI()

Syntax

url.toURI()

Parameter: This method do not accept any parameter.

Return type: This function returns a URI object which is converted from this URL object.

Exception: This function throws URISyntaxException if this URL is not formatted strictly according to RFC2396 and cannot be converted to a URI.

Below examples will illustrate the use of toURI() function:

Example 1:




// Java program to convert URL to URI
  
import java.net.*;
  
class GFG {
    public static void main(String args[])
    {
  
        // url and uri objects
        URL url = null;
        URI uri = null;
  
        try {
  
            // create a URL
            url = new URL("https://www.geeksforgeeks.org");
  
            // display the URL
            System.out.println("URL: " + url);
  
            // convert the URL to URI
            uri = url.toURI();
  
            // display the URI
            System.out.println("URI: " + uri);
        }
        // if any error occurs
        catch (Exception e) {
  
            // display the error
            System.out.println(e);
        }
    }
}


Output:

URL: https://www.geeksforgeeks.org
URI: https://www.geeksforgeeks.org

Example 2:




// Java program to convert URL to URI
  
import java.net.*;
  
class GFG {
    public static void main(String args[])
    {
  
        // url and uri objects
        URL url = null;
        URI uri = null;
  
        try {
  
            // create an invalid URL
            url = new URL("https://www.geeksfor>geeks.com");
  
            // display the URL
            System.out.println("URL: " + url);
  
            // convert the URL to URI
            uri = url.toURI();
  
            // display the URI
            System.out.println("URI: " + uri);
        }
        // if any error occurs
        catch (Exception e) {
  
            // display the error
            System.out.println(e);
        }
    }
}


Output:

URL: https:// www.geeksfor>geeks.com
java.net.URISyntaxException:
 Illegal character in authority at index 8:
 https:// www.geeksfor>geeks.com
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6746 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS