Back to Java
2026-01-196 min read

UUID Generator (Java)

Learn UUID Generator (Java) step by step with clear examples and exercises.

Why This Matters

In software development, it's crucial to have a reliable method for generating unique identifiers that can be used across various platforms and applications. UUIDs (Universally Unique Identifiers) are designed to provide this functionality, ensuring the uniqueness of each identifier in distributed systems, databases, network programming, and more. This tutorial will guide you through creating your own UUID generator using Java, helping you understand the importance and practical applications of UUIDs in programming.

Prerequisites

To follow along with this tutorial, you should have a solid understanding of Java programming concepts, including:

  • Variables and data types
  • Methods and functions
  • Classes and objects
  • Exception handling
  • Interfaces
  • Stream API

Additionally, it's helpful to be familiar with the Java Standard Library, specifically the java.util.UUID class and its related interfaces like UUIDGenerator, UUIDRandomProvider, and SecureRandom.

Core Concept

The java.util.UUID class in Java provides a simple way to generate UUIDs using various methods. The class offers several methods for creating UUIDs, including:

  1. randomUUID(): generates a new UUID using a cryptographically secure random number generator.
  2. fromString(String str): creates a UUID from a string representation of the identifier.
  3. fromTime(long mostSigBits): generates a UUID based on the most significant bits of the current time, specified as a long value in milliseconds since the Unix epoch (January 1, 1970).
  4. fromTime_v1(long timestamp_low, long timestamp_mid, int node, short clock_seq_hi_and_variant): creates a UUID using a combination of the specified parameters, which include a timestamp, node identifier, clock sequence number, and variant.
  5. fromUUIDBytes(byte[] mostSigBits): generates a UUID from an array of bytes representing the most significant bits of the identifier.
  6. nameUUIDFromBytes(byte[] name): creates a UUID based on the MD5 hash of a byte array representing the input name.
  7. createTempUUID(): generates a temporary UUID that is not guaranteed to be unique across multiple Java Virtual Machines (JVMs).
  8. getMostSignificantBits(): returns the most significant 64 bits of the UUID as a long value.
  9. getLeastSignificantBits(): returns the least significant 64 bits of the UUID as a long value.
  10. toString(): converts the UUID to its string representation, which includes hyphens and hexadecimal digits.

Generating a UUID using a custom node identifier

To generate a UUID using a custom node identifier, you can create a new UUID instance by calling the fromTime_v1() method with the specified parameters:

long timestamp = System.currentTimeMillis();
int nodeId = 0x12345678; // Custom node identifier
short clockSeqHiAndVariant = (short) 0x8000; // Clock sequence number and variant
UUID uuid = UUID.fromTime_v1(timestamp, 0, nodeId, clockSeqHiAndVariant);

Generating a UUID based on the MD5 hash of a given name

To generate a UUID based on the MD5 hash of a given name, you can use the nameUUIDFromBytes() method with the name's bytes obtained from its character array:

String name = "MyName";
char[] nameChars = name.toCharArray();
byte[] nameBytes = new byte[16]; // 128-bit UUID requires 16 bytes
Arrays.fill(nameBytes, (byte) 0);

for (int i = 0; i < nameChars.length && i < nameBytes.length; ++i) {
char c = nameChars[i];
nameBytes[i * 2] = (byte) (c >>> 8);
nameBytes[i * 2 + 1] = (byte) (c & 0xFF);
}

UUID uuid = UUID.nameUUIDFromBytes(nameBytes);

Worked Example

Let's create a simple Java program that generates and prints UUIDs using various methods from the java.util.UUID class:

import java.security.SecureRandom;
import java.util.Arrays;
import java.util.UUID;
import java.util.stream.Stream;

public class UUIDGenerator {
public static void main(String[] args) {
System.out.println("Generating a UUID using randomUUID():");
UUID uuid1 = UUID.randomUUID();
System.out.println(uuid1);

System.out.println("\nGenerating a UUID from a string:");
String strUuid = "11111111-2222-3333-4444-555555555555";
UUID uuid2 = UUID.fromString(strUuid);
System.out.println(uuid2);

System.out.println("\nGenerating a UUID based on the current time:");
Random random = new SecureRandom();
long timestamp = System.currentTimeMillis() + (random.nextInt(1L << 32));
UUID uuid3 = UUID.fromTime_v1(timestamp, 0, 0, 0);
System.out.println(uuid3);

System.out.println("\nGenerating a UUID from an array of bytes:");
String name = "MyName";
char[] nameChars = name.toCharArray();
byte[] nameBytes = new byte[16]; // 128-bit UUID requires 16 bytes
Arrays.fill(nameBytes, (byte) 0);

for (int i = 0; i < nameChars.length && i < nameBytes.length; ++i) {
char c = nameChars[i];
nameBytes[i * 2] = (byte) (c >>> 8);
nameBytes[i * 2 + 1] = (byte) (c & 0xFF);
}
UUID uuid4 = UUID.nameUUIDFromBytes(nameBytes);
System.out.println(uuid4);

System.out.println("\nGenerating a temporary UUID:");
UUID uuid5 = UUID.createTempUUID();
System.out.println(uuid5);
}
}

When you run this program, it will generate and print five different UUIDs using the randomUUID(), fromString(), fromTime_v1(), nameUUIDFromBytes(), and createTempUUID() methods.

Common Mistakes

  1. Forgetting to import the necessary classes: Make sure to import both the java.util.UUID class, SecureRandom for generating secure random numbers, and any other required classes at the beginning of your program.
  2. Not handling exceptions: When using methods that may throw exceptions, such as fromString(), it's essential to include exception handling code to ensure your program continues running smoothly.
  3. Misunderstanding the output format: UUIDs are typically represented as strings containing hyphens and hexadecimal digits. Be aware of this format when comparing or storing UUID values.
  4. Using non-secure random number generators: When generating UUIDs based on time, use a secure random number generator like SecureRandom to ensure the uniqueness of your identifiers.
  5. Not understanding the difference between temporary and non-temporary UUIDs: Temporary UUIDs are not guaranteed to be unique across multiple JVMs, so use them carefully when identifying resources within a single JVM.

Common Mistakes - Generating a UUID using a custom node identifier

  1. Incorrect node identifier format: The node identifier should be a 32-bit integer represented as an int or a hexadecimal string with the prefix "0x".
  2. Clock sequence number and variant misunderstanding: The clock sequence number is used to detect duplicate UUIDs within a short time frame, while the variant determines the version of the UUID. By default, both are set to 0.

Practice Questions

  1. Write a method that generates a UUID using the current time (similar to uuid3 in our example). Use a secure random number generator for added security.
  2. Create a class with a static method that accepts a custom node identifier and generates a UUID using the fromTime_v1() method (as shown in our example).
  3. Write a method that generates a UUID based on the MD5 hash of a given name, similar to the nameUUIDFromBytes() method but accepting a string instead of a byte array.
  4. Implement a Java Stream API solution for generating multiple UUIDs using the randomUUID() method and collecting them in a List.

FAQ

How are UUIDs generated?

UUIDs are generated using a combination of time, a random number, and sometimes additional parameters like a node identifier or clock sequence number. The specific method used to generate a UUID can vary depending on the programming language and application requirements. In Java, you can use various methods provided by the java.util.UUID class to create UUIDs.

Are all UUIDs unique?

Yes, by design, UUIDs are intended to be globally unique across space and time. However, Note that that while the probability of generating two identical UUIDs is extremely low, it is not mathematically impossible.

How can I compare two UUIDs in Java?

To compare two UUIDs in Java, you can use the equals() method provided by the UUID class. This method checks if both UUIDs have the same value (regardless of their string representation). Alternatively, you can compare the most significant and least significant bits of the UUID using the getMostSignificantBits() and getLeastSignificantBits() methods.

UUID uuid1 = ...;
UUID uuid2 = ...;
if(uuid1.equals(uuid2)) {
System.out.println("The UUIDs are equal.");
} else {
System.out.println("The UUIDs are not equal.");
}

long mostSigBits1 = uuid1.getMostSignificantBits();
long mostSigBits2 = uuid2.getMostSignificantBits();
if(mostSigBits1 == mostSigBits2) {
System.out.println("The UUIDs have the same most significant bits.");
} else {
System.out.println("The UUIDs have different most significant bits.");
}
UUID Generator (Java) | Java | XQA Learn