Java - get domain name from given url

3 points
Created by:

In this article, we would like to show how to get a domain from a given URL in Java.

Quick solution:

// import;

String url = "";

URI uri = new URI(url);
String host = uri.getHost();
String domain = host.startsWith("www.") ? host.substring(4) : host;

System.out.println(domain);  //


Practical example

In this section, the code was split to provide reusable DomainUtil class. file:


public class Program {

    public static void main(String[] args) throws URISyntaxException {
        String url = "";
        String domain = DomainUtil.getDomainName(url);
        Syste.out.println(domain); //

Example output: file:


public class DomainUtil {

    public static String getDomainName(String url) throws URISyntaxException {
        URI uri = new URI(url);
        String host = uri.getHost();
        return host.startsWith("www.") ? host.substring(4) : host;
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂