Java program to check for URL in a String

Java 8Object Oriented ProgrammingProgramming

A program can be created to check if a string is a correct URL or not. An example of an URL is given as follows −

String = https://www.wikipedia.org/
The above string is a valid URL

A program that demonstrates this is given as follows.

Example

 Live Demo

import java.net.URL;
public class Example {
   public static boolean check_URL(String str) {
   try {
      new URL(str).toURI();
      return true;
   }catch (Exception e) {
      return false;
   }
}
public static void main(String[] args) {
   String str = "http://www.wikipedia.org/";
   System.out.println("String = " + str);
   if (check_URL(str))
      System.out.println("The above string is a URL");
   else
      System.out.println("The above string is not a URL");
   }
}

Output

String = http://www.wikipedia.org/
The above string is a URL

Now let us understand the above program.

In the function check_URL(), a URL object is created. If there is no exception when the object is created, then true is returned. Otherwise, false is returned. The code snippet that demonstrates this is given as follows.

public static boolean check_URL(String str) {
   try {
      new URL(str).toURI();
      return true;
   }catch (Exception e) {
      return false;
   }
}

In the function main(), the string is printed. Then the function check_URL() is called with string str. If true is returned, then str is a URL and that is printed otherwise str is not a URL and that is printed. The code snippet that demonstrates this is given as follows.

public static void main(String[] args) {
   String str = "http://www.wikipedia.org/";
   System.out.println("String = " + str);
   if (check_URL(str))
      System.out.println("The above string is a URL");
   else
      System.out.println("The above string is not a URL");
}
raja
Published on 06-Dec-2018 11:56:25
Advertisements