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 invalidUUID 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;
}