Check if a website exists or not in Java

In this Java program, we check whether a URL is valid or not i.e whether the website exists or not.

To start the implementation, we follow the following steps:

  1. We input the URL which we want to check if exists or not as a String.
  2. We use the class to validate the URL.
  3. We then create a URL object from the inputted String using the toURI() method.
  4. If we get an exception, we return false and the website does not exist.
  5. But if there is no exception, we return true and the website exists.

Let’s understand what the toURI() method does exactly.

toURI() method:

  • 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.
  • The syntax is .toURI()  and it does not accept any parameter.
  • It returns a URI object which is converted from this URL object.
  • It throws URISyntaxException if this URL is not formatted strictly according to RFC2396 and cannot be converted to a URI.
  • eg: if URL given is then there will be no exception and error.
    But, if the URL given is there will be an exception and error will be displayed since this URL does not exist.
    Error will be

Let us now implement the code.

Code to check if a website exists or not in Java:

class ValidWebsite
  public static boolean isValid(String url) 
    try            // Try creating a valid URL //
         new URL(url).toURI(); 
         return true; 
          catch (Exception e)         // If there is an Exception while creating the URL object return false since it is invalid
              return false; 
  public static void main(String[] args)throws IOException
    String url=""; 		//Input String which is the website to be checked if it exists or not	
    BufferedReader br = new BufferedReader(new InputStreamReader(;
    System.out.println("Enter the URL: ");
    url= br.readLine();
        if (isValid(url))  
            System.out.println("The inputted website exists"); 
            System.out.println("The inputted website does not exist\nPlease try again");                    

Hence we have successfully implemented the program.
Note: Please input the URL properly and check the syntax and do not forget the “https://” which comes in the start.


The importance of the syntax of the inputted website is shown below in the following outputs.

Enter the URL:
The inputted website exists
Enter the URL: 
The inputted website does not exist
Please try again
Enter the URL: 
The inputted website does not exist
Please try again

As shown above, we have found out if the following websites exist or do not exist and hence the program is successfully implemented.

Also, read:


Leave a Reply

Your email address will not be published. Required fields are marked *