Generate UUID in Java

Table of Contents:

  1. Introduction to UUID
  2. Generating UUID using java.util.UUID
  3. Generating UUID using java.util.Random
  4. Generating UUID using Apache Commons
  5. Summary

Introduction to UUID

A UUID (Universally Unique Identifier) is a 128-bit identifier that is globally unique. It is often used to uniquely identify resources across different systems. In Java, the java.util.UUID class provides various methods to generate UUIDs.

Generating UUID using java.util.UUID

The java.util.UUID class provides a randomUUID() method that generates a random UUID. Here's an example:

import java.util.UUID;

public class UUIDGenerator {
    public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        System.out.println("Generated UUID: " + uuid.toString());
    }
}

Generating UUID using java.util.Random

Another way to generate UUIDs in Java is by using the java.util.Random class. Here's an example:

import java.util.Random;

public class UUIDGenerator {
    public static void main(String[] args) {
        Random random = new Random();
        long mostSignificantBits = random.nextLong();
        long leastSignificantBits = random.nextLong();
        UUID uuid = new UUID(mostSignificantBits, leastSignificantBits);
        System.out.println("Generated UUID: " + uuid.toString());
    }
}

Generating UUID using Apache Commons

Apache Commons provides a library called "commons-lang" which includes a RandomStringUtils class that can be used to generate UUIDs. Here's an example:

import org.apache.commons.lang3.RandomStringUtils;

public class UUIDGenerator {
    public static void main(String[] args) {
        String uuid = RandomStringUtils.random(32, true, true);
        System.out.println("Generated UUID: " + uuid);
    }
}

Summary

In this tutorial, we discussed different ways to generate UUIDs in Java. We explored the java.util.UUID class, the java.util.Random class, and the Apache Commons library. You can choose the method that best suits your requirements and use it to generate unique identifiers for your applications.

References: