I need a Java code which accepts an URL like http://www.example.com and displays whether the format of URL is correct or not.
Based on the answer from @adarshr I would say it is best to use the URL class instead of the URI class, the reason for it being that the URL class will mark something like htt://example.com as invalid, while URI class will not (which I think was the goal of the question).
//if urlStr is htt://example.com return value will be false
public boolean isValidURL(String urlStr) {
    try {
      URL url = new URL(urlStr);
      return true;
    }
    catch (MalformedURLException e) {
        return false;
    }
}
                        This should do what you're asking for.
public boolean isValidURL(String urlStr) {
    try {
      URL url = new URL(urlStr);
      return true;
    }
    catch (MalformedURLException e) {
        return false;
    }
}
Here's an alternate version:
public boolean isValidURI(String uriStr) {
    try {
      URI uri = new URI(uriStr);
      return true;
    }
    catch (URISyntaxException e) {
        return false;
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With