Java
Java

 

Learn how to create a simple URL shortener using Java. This project demonstrates how to take a long URL and convert it into a short, SEO-friendly version.

Introduction

A URL shortener is a tool that takes a long URL and converts it into a shorter, more manageable version. The shortened URL redirects to the original URL when clicked. This is a popular technique used for social media sharing and to make links more user-friendly. In this tutorial, we will create a simple URL shortener using the Java programming language.

Objective

The goal of this project is to write a simple Java program that will take a long URL and convert it into a short, SEO-friendly URL. The program will store these short URLs in a database or a simple data structure, and allow redirection to the original URL when needed.

Java Code for URL Shortener

import java.util.HashMap;
import java.util.Random;

public class URLShortener {
    private static final String BASE_URL = "http://short.ly/";
    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static HashMap<String, String> urlDatabase = new HashMap<>();
    private static Random random = new Random();

    // Method to generate a random short URL code
    public static String generateShortCode() {
        StringBuilder shortCode = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(CHARACTERS.length());
            shortCode.append(CHARACTERS.charAt(index));
        }
        return shortCode.toString();
    }

    // Method to shorten the URL
    public static String shortenURL(String longURL) {
        // Check if the URL is already in the database
        if (urlDatabase.containsValue(longURL)) {
            for (String key : urlDatabase.keySet()) {
                if (urlDatabase.get(key).equals(longURL)) {
                    return BASE_URL + key;
                }
            }
        }
        
        // Generate a new short code and store the URL
        String shortCode = generateShortCode();
        urlDatabase.put(shortCode, longURL);
        return BASE_URL + shortCode;
    }

    // Method to retrieve the original URL from the short code
    public static String getOriginalURL(String shortCode) {
        return urlDatabase.get(shortCode);
    }

    public static void main(String[] args) {
        // Test the URL shortener
        String longURL = "https://www.example.com";
        String shortURL = shortenURL(longURL);
        System.out.println("Shortened URL: " + shortURL);

        // Get the original URL from the short code
        String shortCode = shortURL.replace(BASE_URL, "");
        String originalURL = getOriginalURL(shortCode);
        System.out.println("Original URL: " + originalURL);
    }
}

Explanation of the Program

This Java program provides a simple implementation of a URL shortener with the following components:

  • BASE_URL: The base URL used for generating the short links (e.g., “http://short.ly/”).
  • CHARACTERS: A string containing characters that can be used to generate the short URL code.
  • urlDatabase: A HashMap used to store the mapping of short URL codes to their original long URLs.
  • generateShortCode: A method that generates a random 6-character short code by selecting random characters from the CHARACTERS string.
  • shortenURL: A method that takes a long URL as input, checks if it already exists in the database, and if not, generates a new short code for it.
  • getOriginalURL: A method that takes a short code as input and retrieves the original long URL from the database.
  • main: The main method that tests the functionality of the URL shortener by shortening a URL and retrieving the original URL from the short code.

How to Run the Program

  1. Ensure that you have Java installed on your machine. You can download it from Oracle’s official website.
  2. Save the provided Java code in a file named URLShortener.java.
  3. Open a terminal or command prompt and navigate to the directory where the URLShortener.java file is saved.
  4. Compile the Java program by running the following command:
    javac URLShortener.java
  5. Run the compiled Java program using the command:
    java URLShortener
  6. You will see the shortened URL and the corresponding original URL printed on the console.
© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

49 thoughts on “URL Shortener in Java”
  1. I do not even understand how I ended up right here, however I thought
    this put up used to be great. I don’t realize who you might be but
    certainly you’re going to a famous blogger when you aren’t already.
    Cheers!

  2. After looking at a few of the blog posts on your web page, I honestly like your technique of blogging.

    I saved as a favorite it to my bookmark webpage list and will be checking back in the
    near future. Please check out my web site too and let
    me know how you feel.

  3. Hello! I know this is kind of off-topic however
    I needed to ask. Does building a well-established website such as yours require a lot of work?
    I am completely new to operating a blog however I do write in my diary every day.
    I’d like to start a blog so I can easily share my
    personal experience and thoughts online. Please let me know if
    you have any kind of recommendations or tips for new
    aspiring blog owners. Thankyou!

  4. Hi! I know this is kinda off topic but I was wondering which blog platform are you
    using for this website? I’m getting tired of WordPress because I’ve had problems
    with haxkers and I’m looking at options for another
    platform. I would be fantastic if you could point me in the direction of a
    good platform.

  5. That is really interesting, You’re a very professional blogger.
    I have joined your rss feed and stay up for in search of more
    of your great post. Also, I’ve shared your site in my social networks

  6. I think what you said made a great deal of sense. But,
    think on this, what if you were to create a awesome headline?
    I ain’t saying your content is not good, but what if you added
    something that makes people desire more? I mean URL
    Shortener in Java – Learn Programming is a little plain. You might peek at Yahoo’s front page and see how they create article titles
    to get people interested. You might add a related video or a related pic
    or two to grab people excited about what you’ve written. In my
    opinion, it could bring your website a little livelier.

  7. Woah! I’m really loving the template/theme of this website.
    It’s simple, yet effective. A lot of times it’s
    difficult to get that “perfect balance” between usability and
    visual appearance. I must say you have dolne a amazing job with this.

    In addition, the blog loads extremely fast for me on Opera.
    Exceptional Blog!

  8. Hi! This is my first comment here so I just wanted to give a quick shout out and say I really enjoy reading your posts.
    Can you recommend any other blogs/websites/forums that cover
    the same subjects? Thank you so much!

  9. An impressive share! I’ve just forwarded this onto a friend who has been conducting a little homework on this.
    And he actually bought me lunch due to the fact
    that I stumbled upon it for him… lol. So let me
    reword this…. Thank YOU for the meal!! But
    yeah, thanks for spending time to talk about this topic here on your web
    page.

  10. I don’teven know how I stopped up right here, however I assumed this
    submit used to be great. I do not know who you’re but definitely
    you’re going to a famous blogger in case you aren’t already.
    Cheers!

  11. We are a bunch of volunteers and opening a brand new scheme in our community.
    Your site provided us with valuable information to work on. You’ve performed a formidable task and
    our whole group can be thankful to you.

  12. I’m really impressed together with your writing talents and also
    with the layout to your weblog. Is this a paid topic or did
    you customize it yourself? Either way keep up the excellent high quality writing,
    it’s rare to peer a nice weblog like this one nowadays..

  13. Hey! I know this is kinda off topic but I’d figured I’d ask.
    Would you be interested in trading links or maybe guest authoring a blog article or vice-versa?
    My website goes over a lot of the same subjects as yours and I
    feel we could greatly benefit from each other. If you happen to be
    interested feel free to send me an email. I look forward to hearing from you!
    Excellent blog by the way!

  14. When someone writes an article he/she maintains the image of a user in his/her
    brain that how a user can know it. Therefore that’s why this paragraph
    is outstdanding. Thanks!

  15. Hi there! I could have sworn I’vebeen to this web site before but after looking at a few of the articles I realized it’s new to me.

    Nonetheless, I’m definitely delighted I came across it and I’ll be book-marking it and
    checking back regularly!

  16. Привет всем!
    Долго обмозговывал как поднять сайт и свои проекты и нарастить ИКС Яндекса и узнал от крутых seo,
    крутых ребят, именно они разработали недорогой и главное буст прогон Xrumer – https://www.bing.com/search?q=bullet+%D0%BF%D1%80%D0%BE%D0%B3%D0%BE%D0%BD
    Xrumer 2025: советы по настройке помогают использовать программу эффективно. Правильные параметры ускоряют прогон ссылок. Это повышает DR и авторитет сайта. Советы опытных специалистов упрощают работу. Xrumer 2025: советы по настройке – ценный ресурс для SEO.
    seo аудит что такое, продвижение сайта на примере, Xrumer рассылка форумов
    линкбилдинг цена, стратегия продвижения сайтов, в seo php
    !!Удачи и роста в топах!!

  17. I was curious if you ever thought of changing the layout of your blog?

    Its very well written; I love what youve got to say.
    But maybe you could a little mre in the way of content so people
    could connect with it better. Youve got an awful lot oof tewxt
    for only having 1 or two images. Maybe you
    could space it out better?

  18. You actually make it seem so easy with your presentation but I find this matter to be really something which I think I would never understand.
    It seems too complex and extremely broad for me.
    I am looking forward for your next post, I will try to get the
    hang of it!

  19. You really make it seem so easy with your presentation but I find this matter
    to be really something that I think I would never understand.
    It seems too complicated and very broad for me. I am looking forward
    for your next post, I’ll try to get the hang of it!

  20. I have been exploring for a little bit for any high-quality articles or blog posts on this sort of space .
    Exploring in Yahoo I ultimately stumbled upon this website.
    Studying this info So i’m happy to convey that I
    have a very just right uncanny feeling I came upon just what I needed.
    I so much definitely will make certain to don?t put out of your mind this website and provides it a glance on a constant basis.

  21. Nice weblog right here! Additionally your site so much
    up fast! What host are you the use of? Can I get your affiliate
    hyperlink in your host? I desire my web site loaded up as quickly as yours lol

  22. Nice post. I used to be checking constantly this weblog and I am impressed!
    Very useful information specifically the ultimate part 🙂 I care for such
    info much. I was looking for this certain information for a long time.
    Thank you and good luck.

Leave a Reply to https://dreamproxies.com/buy-proxies/1000-private-proxies Cancel reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)