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*;public class URLValidator{   String validURL = "" ;   String inValidURL = "" ;      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 URLValidator valid: trueException: no protocol: valid: false*/ 
See also  Java Developer Jobs: Your Guide to Landing the Perfect Position in 2024

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