Java UUID
Last modified: July 17, 2026
This Java UUID tutorial shows how to work with the java.util.UUID
class for generating and manipulating universally unique identifiers.
UUID
A UUID (Universally Unique Identifier) is a 128-bit value that is unique across both space and time. It is defined by RFC 9562. The standard 128-bit space is vast enough that the probability of a collision is negligible for practical purposes.
Common use cases include:
- Database primary keys — UUIDs avoid
AUTO_INCREMENTcontention in replicated or sharded databases and let clients generate keys without a round trip to the server - Session and token identifiers — web applications use UUIDs as session cookies, CSRF tokens, and API keys because they are unguessable and require no central store for uniqueness
- Distributed tracing — each request in a microservice architecture is assigned a UUID that propagates across service boundaries, linking logs and metrics into a single trace
- File and object storage — object stores (S3, cloud storage) use UUID-like names to avoid naming conflicts when millions of users upload content concurrently
- Event sourcing and messaging — events and messages carry a UUID so consumers can detect duplicates and maintain idempotent processing
- Offline-first applications — mobile and desktop apps generate UUIDs locally while offline and synchronise later without collisions
A UUID is represented as a 36-character hexadecimal string in the standard 5-group format:
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
For example: 550e8400-e29b-41d4-a716-446655440000
Creating UUIDs
The java.util.UUID class provides several ways to create UUID
instances.
Random UUID (v4)
The randomUUID method generates a random (version 4) UUID
using a cryptographically strong pseudo-random number generator.
void main() {
UUID uuid = UUID.randomUUID();
System.out.println(uuid);
}
$ java Main.java 550e8400-e29b-41d4-a716-446655440000
UUID from string
The fromString method parses a UUID from its standard string
representation.
void main() {
String uuidStr = "550e8400-e29b-41d4-a716-446655440000";
UUID uuid = UUID.fromString(uuidStr);
System.out.println(uuid);
}
$ java Main.java 550e8400-e29b-41d4-a716-446655440000
Name-based UUID (v3)
The nameUUIDFromBytes method generates a name-based UUID
using MD5 hashing (version 3). Given the same name, it always produces
the same UUID.
void main() {
byte[] name = "zetcode.com".getBytes();
UUID uuid = UUID.nameUUIDFromBytes(name);
System.out.println(uuid);
}
$ java Main.java 3b6c28b0-cefe-38bc-95aa-07c3df440a82
UUID from bits
The UUID constructor accepts two long values representing
the 64 most significant bits and the 64 least significant bits.
void main() {
long msb = 0x550e8400e29b41d4L;
long lsb = 0xa716446655440000L;
UUID uuid = new UUID(msb, lsb);
System.out.println(uuid);
}
$ java Main.java 550e8400-e29b-41d4-a716-446655440000
UUID versions
There are several versions of UUIDs, each serving a different purpose:
| Version | Name | Description |
|---|---|---|
| v1 | Time-based | Generated from a timestamp and MAC address; unique across time and space |
| v3 | Name-based (MD5) | Generated by hashing a namespace and name with MD5; deterministic |
| v4 | Random | Generated from random or pseudo-random numbers; most common |
| v5 | Name-based (SHA-1) | Generated by hashing a namespace and name with SHA-1; deterministic |
| v7 | Unix time-based | Generated from a Unix timestamp with random suffix; sortable by creation time |
Java's built-in UUID class directly supports v3 (nameUUIDFromBytes)
and v4 (randomUUID). For v1, v5, and v7, external libraries or
a custom implementation are required.
UUID fields
We can inspect the internal structure of a UUID and extract its fields.
void main() {
UUID uuid = UUID.randomUUID();
System.out.printf("UUID: %s%n", uuid);
System.out.printf("Version: %d%n", uuid.version());
System.out.printf("Variant: %d%n", uuid.variant());
System.out.printf("Most significant bits: 0x%016x%n",
uuid.getMostSignificantBits());
System.out.printf("Least significant bits: 0x%016x%n",
uuid.getLeastSignificantBits());
}
The version method returns the UUID version number (4 for
random UUIDs). The variant method returns the variant number
(2 for the standard RFC variant). The getMostSignificantBits
and getLeastSignificantBits methods return the 128-bit value
as two long values.
$ java Main.java UUID: 550e8400-e29b-41d4-a716-446655440000 Version: 4 Variant: 2 Most significant bits: 0x550e8400e29b41d4 Least significant bits: 0xa716446655440000
Comparing UUIDs
UUID implements Comparable and can be compared and sorted.
void main() {
UUID u1 = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
UUID u2 = UUID.fromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
System.out.printf("u1: %s%n", u1);
System.out.printf("u2: %s%n", u2);
System.out.printf("u1.compareTo(u2): %d%n", u1.compareTo(u2));
System.out.printf("u1.equals(u2): %b%n", u1.equals(u2));
System.out.printf("u1.hashCode(): %d%n", u1.hashCode());
}
The compareTo method compares UUIDs by their most significant
bits first, then by their least significant bits. Two UUIDs are equal if
both bit halves match.
$ java Main.java u1: 550e8400-e29b-41d4-a716-446655440000 u2: 6ba7b810-9dad-11d1-80b4-00c04fd430c8 u1.compareTo(u2): -1 u1.equals(u2): false u1.hashCode(): 381119164
Sorting UUIDs
Since UUID is Comparable, UUIDs can be sorted in collections.
void main() {
var uuids = new ArrayList<UUID>();
for (int i = 0; i < 5; i++) {
uuids.add(UUID.randomUUID());
}
Collections.sort(uuids);
for (UUID uuid : uuids) {
System.out.println(uuid);
}
}
We generate five random UUIDs and sort them using
Collections.sort. Sorting is performed by comparing the
most significant bits, then the least significant bits.
$ java Main.java 035141fc-9241-4826-a0f8-86458e34ab93 30ca1d0d-87cf-4f39-a563-045dff9ae896 b5442b5b-0354-4795-90c0-31a44438d9c3 cbde4ecc-ce7f-49a8-9245-f9701ddbcf55 f68bc94c-4a2b-4d0e-a302-13c35d0ad837
We can also sort UUIDs by their string representation using
Comparator.comparing(String::valueOf):
void main() {
var uuids = new ArrayList<UUID>();
IntStream.range(0, 5).forEach(i -> uuids.add(UUID.randomUUID()));
Collections.sort(uuids, Comparator.comparing(String::valueOf));
for (UUID uuid : uuids) {
System.out.println(uuid);
}
}
The IntStream.range generates a sequence of indices passed
to a lambda that adds random UUIDs to the list.
Comparator.comparing(String::valueOf) sorts the UUIDs by their
string representation, which produces lexicographic ordering rather than
numeric ordering by bit values.
UUID as byte array
We can convert a UUID to and from a 16-byte array for storage or transmission.
void main() {
UUID uuid = UUID.randomUUID();
System.out.println("Original: " + uuid);
// UUID to byte array
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
byte[] bytes = bb.array();
// Byte array back to UUID
ByteBuffer bb2 = ByteBuffer.wrap(bytes);
UUID uuid2 = new UUID(bb2.getLong(), bb2.getLong());
System.out.println("Restored: " + uuid2);
}
We use a ByteBuffer to pack the two long values
into a 16-byte array and then reconstruct the UUID from the array.
$ java Main.java Original: 550e8400-e29b-41d4-a716-446655440000 Restored: 550e8400-e29b-41d4-a716-446655440000
Source
Java UUID - Language Reference
In this article, we have worked with the Java UUID class.
Author
List all Java tutorials.