Generate UUIDs in Java

Resources  |  Generate UUIDs in Java

Generating a UUID in Java is straightforward thanks to the built-in java.util.UUID class. Below are examples of how to generate a UUID using this class:

Basic UUID Generation

The UUID class in Java provides a simple way to generate a random UUID (UUIDv4). Here's an example:

import java.util.UUID;

public class GenerateUUID {
    public static void main(String[] args) {
        // Generate a new UUID
        UUID uuid = UUID.randomUUID();

        // Output the generated UUID
        System.out.println("Generated UUID: " + uuid.toString());
    }
}

Explanation

  • UUID.randomUUID(): This method generates a random UUID (UUIDv4).
  • uuid.toString(): This method converts the UUID to its string representation.

Running the Code

  1. Save the Code: Save the code above in a file named GenerateUUID.java.

  2. Compile the Code: Open your terminal and navigate to the directory where you saved the file, then compile the code using the javac command:

    javac GenerateUUID.java
    
  3. Run the Code: Run the compiled class using the java command:

    java GenerateUUID
    

Output Example

When you run the code, the output will be similar to:

Generated UUID: 123e4567-e89b-12d3-a456-426614174000

Each time you run the program, a different UUID will be generated.

Generating UUID from Name (UUIDv3 and UUIDv5)

You can also generate a UUID from a namespace and a name using the MD5 (UUIDv3) or SHA-1 (UUIDv5) hashing algorithms. Here's an example of how to generate a UUIDv5 (SHA-1 based):

import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class GenerateNameBasedUUID {
    public static void main(String[] args) {
        // Define a namespace UUID (e.g., the DNS namespace)
        UUID namespaceUUID = UUID.fromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8");

        // Define the name for which the UUID will be generated
        String name = "example.com";

        // Generate a UUIDv5 (SHA-1 based) using the namespace and name
        UUID uuid = UUID.nameUUIDFromBytes((namespaceUUID.toString() + name).getBytes(StandardCharsets.UTF_8));

        // Output the generated UUID
        System.out.println("Generated UUIDv5: " + uuid.toString());
    }
}

Explanation

  • UUID.nameUUIDFromBytes(byte[] name): This method generates a UUID based on the byte array of the concatenation of the namespace UUID and the name. The result is a UUIDv3 (MD5 based) or UUIDv5 (SHA-1 based) depending on the algorithm used internally by the method.

Summary

Here are the key steps to generate a UUID in Java:

  1. Generate a random UUID:

    UUID uuid = UUID.randomUUID();
    
  2. Generate a name-based UUID:

    UUID uuid = UUID.nameUUIDFromBytes((namespaceUUID.toString() + name).getBytes(StandardCharsets.UTF_8));
    

By using the UUID class, you can easily generate both random and name-based UUIDs in Java for various purposes.