- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to check for URL in a String
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
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"); }
Advertisements