Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Check if URL is valid or not in Java

  • Last Updated : 30 May, 2018

Given a URL as string, we need to find if the given URL is valid or not.

Input : str = ""
Output : Yes

Input : str = "https://"
Output : No
Note that there is a space after https://

We can use class to validate a URL. The idea is to create a URL object from the specified String representation. If we do not get exception while creating the object, we return true. Else we return false.

// Java program to check if a URL is valid 
// using
class Test {
    /* Returns true if url is valid */
    public static boolean isValid(String url)
        /* Try creating a valid URL */
        try {
            new URL(url).toURI();
            return true;
        // If there was an Exception
        // while creating URL object
        catch (Exception e) {
            return false;
    /*driver function*/    
    public static void main(String[] args)
        String url1 = "";
        if (isValid(url1)) 
        String url2 = "http://";
        if (isValid(url2)) 



This article is contributed by Pranav . If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!