Generate UUID v4 and v7 in Java
Copy-paste Java code that produces a UUID v4 (random, the long-standing default) or UUID v7 (time-ordered, the modern choice for database keys). Both blocks below are production-ready.
UUID v4 in Java
v4 is purely random — 122 bits of entropy, no structure. Use it when you don't want timing information embedded in the ID, or when you don't care about index locality.
import java.util.UUID;
public class Example {
public static void main(String[] args) {
UUID id = UUID.randomUUID(); // v4
System.out.println(id);
}
}
UUID v7 in Java
v7 embeds a millisecond Unix timestamp in the first 48 bits, so the IDs sort chronologically. This is what modern databases want from a primary key — sequential inserts land in adjacent index pages instead of scattering writes.
// JDK 25+ ships native UUID v7 via UUID.timeOrderedEpochUUID()
// (October 2025 release). For earlier JDKs, use 'java-uuid-generator':
//
// <dependency>
// <groupId>com.fasterxml.uuid</groupId>
// <artifactId>java-uuid-generator</artifactId>
// <version>5.0.0</version>
// </dependency>
import com.fasterxml.uuid.Generators;
import java.util.UUID;
public class Example {
public static void main(String[] args) {
UUID id = Generators.timeBasedEpochGenerator().generate();
System.out.println(id);
}
}
Library support
JDK 25 (October 2025 LTS) added native UUID v7. On JDK 24 and earlier, `java-uuid-generator` (FasterXML, 5.0.0+) is the standard third-party library.
Notes
`UUID.randomUUID()` uses `SecureRandom` under the hood — same primitive as `Math.random()` is not. Safe for IDs without further work.
Need them in bulk?
Our UUID generator produces 1 to 1000 UUIDs (v4 or v7) instantly, all in your browser, with one-click copy and JSON/CSV export. Useful for seeding test data or pre-generating IDs offline.