Code guide

Generate UUIDs in Java

Generate UUIDs in Java with java.util.UUID, parse strings, and add UUID v7 with a maintained library.

Java has a built-in UUID class for version 4. It covers most needs out of the box; time-ordered UUID v7 requires a small, well-maintained library.

Key takeaways

  • UUID.randomUUID() generates a version 4 UUID with no dependencies.
  • UUID.fromString() parses and validates canonical UUID text.
  • For UUID v7, use a maintained library such as uuid-creator.

For implementation context, continue with UUID v4, Kotlin, and UUID v7. These pages cover the closest generator, comparison, validation or storage decisions without repeating this guide.

Generate and parse with the JDK

The standard library covers UUID v4 and parsing. fromString throws IllegalArgumentException for invalid input, which you can catch to validate.

import java.util.UUID;

UUID id = UUID.randomUUID();          // version 4
String text = id.toString();

UUID parsed = UUID.fromString(text);  // throws if invalid

UUID v7 in Java

The JDK does not generate UUID v7. Add a maintained library when you need time-ordered keys for databases and logs.

// com.github.f4b6a3:uuid-creator
import com.github.f4b6a3.uuid.UuidCreator;

UUID v7 = UuidCreator.getTimeOrderedEpoch();

Validate canonical text before using a resource ID

UUID.fromString throws IllegalArgumentException when it cannot parse a value. Catch that at the input boundary. If your API requires the full hyphenated form, also compare the parsed value with the input; this rejects shortened group forms accepted by some JDK implementations.

The example accepts either letter case and emits lowercase text. Reject the all-zero value or require a specific version only when your application contract calls for it. Successful parsing does not establish ownership of the referenced resource.

static UUID parseCanonicalUuid(String input) {
    if (input == null) {
        throw new IllegalArgumentException("UUID is required");
    }
    UUID id = UUID.fromString(input);
    if (!id.toString().equalsIgnoreCase(input)) {
        throw new IllegalArgumentException("Use a full hyphenated UUID");
    }
    return id;
}

FAQ

Generate UUIDs in Java questions

Does java.util.UUID support version 7?

No. UUID.randomUUID() produces version 4. For UUID v7 use a maintained library such as uuid-creator.

How do I validate a UUID in Java?

Call UUID.fromString and catch IllegalArgumentException, or match a strict regex before parsing.

Is UUID.randomUUID thread-safe?

Yes. It is safe to call from multiple threads and uses a secure random source.

Primary references

Standards and technical sources

The implementation and guidance on this page are checked against these standards and platform documentation sources.

Generate UUID in Java - java.util.UUID Examples