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();

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.

Generate UUID in Java - java.util.UUID Examples