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.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)