Friday, September 5, 2025
HomeLanguagesJavaCheck if URL is valid or not in Java

Check if URL is valid or not in Java

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

Input : str = "https://www.geeksforgeeks.org/"
Output : Yes


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

Using java.net.url
We can use java.net.url 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 java.net.url
import java.net.URL;
  
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 = "https://www.geeksforgeeks.org/";
        if (isValid(url1)) 
            System.out.println("Yes");
        else
            System.out.println("No");     
              
        String url2 = "http:// www.geeksforgeeks.org/";
        if (isValid(url2)) 
            System.out.println("Yes");
        else
            System.out.println("No");                
    }
}


Output:

Yes
No

This article is contributed by Pranav . If you like Lazyroar and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the Lazyroar 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.

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6638 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11866 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7028 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS