devxlogo

Validating an URL in Java

Validating an URL in Java

Java has some predefined ways of validating an URL. Here is a code snippet:

import java.net.*;public class URLValidator{   String validURL = "http://google.com" ;   String inValidURL = "httpgoogle.com" ;      public static void main(String args[])   {      URLValidator uRLValidator = new URLValidator();      uRLValidator.proceed();   }   private void proceed()   {      System.out.println(validURL + ": valid: " + validateURL(validURL));      System.out.println();      System.out.println(inValidURL + ": valid: " + validateURL(inValidURL));   }   public boolean validateURL(String urlArg)   {      boolean isValidUrl = false;      try      {         URL url = new URL(urlArg);         isValidUrl = true;      } catch (Exception exception)      {         isValidUrl = false;         System.out.println("Exception: " + exception.getMessage());      }      return isValidUrl;   }}/*Expected output:[root@mypc]# java URLValidatorhttp://google.com: valid: trueException: no protocol: httpgoogle.comhttpgoogle.com: valid: false*/ 
See also  Java Developer Jobs: Your Guide to Landing the Perfect Position in 2024
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist