UUID generation in Java - cover art

Comparisons 14 min read

UUID generation in Java

November 3, 2026 · 14 min read

Java ships UUID support in the standard library: java.util.UUID generates version 4 identifiers and parses canonical strings. Enterprise codebases use UUIDs for JPA primary keys, correlation IDs in SLF4J MDC, and DTO fields in REST responses. The API is small but endianness with MongoDB and legacy drivers still trips teams.

UUID.randomUUID()

UUID.randomUUID() creates a type-4 UUID using a cryptographically strong pseudo-random number generator (implementation-defined but secure on modern JDKs). Prefer it over rolling your own hex strings.

import java.util.UUID;

UUID id = UUID.randomUUID();
String canonical = id.toString(); // lowercase hex with hyphens

UUID.fromString and validation

UUID.fromString accepts the 36-character canonical form. Invalid input throws IllegalArgumentException - map to HTTP 400 in controllers. For optional query params, validate with the UUID validator during integration testing when partners send uppercase or missing hyphens.

Version and variant bits

UUID exposes version() and variant() for debugging. Do not construct version 4 manually unless you have a spec reason; incorrect version nibbles break validators that check RFC bits.

JPA, Hibernate, and column types

MongoDB Java driver and UUID

BSON UUID subtype 0x03 vs 0x04 endianness caused years of confusion. Align driver UuidRepresentation with how data was written. Convert legacy binaries with the MongoDB UUID converter when hex in the shell does not match Java toString().

FAQ

Is randomUUID thread-safe?
Yes. UUID static methods are safe for concurrent calls.
Does Java UUID use lowercase?
toString() returns lowercase hex per common JVM implementations.
How do I convert UUID to bytes?
Use uuidToBytes helpers or ByteBuffer with mostSignificantBits and leastSignificantBits - mind endianness for MongoDB.

Related: UUID generation in Go · Java UUID MongoDB conversion · MongoDB UUID Java driver issues · UUIDs in REST APIs

Browse all tools