Generate UUID in Java

The simplest way to generate a UUID in Java is to use a build in UUID and call its static method randomUUID. Note that this will produce a valid version 4 UUID.


import java.util.UUID;

class UUIDGenerator {
    public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        System.out.println("Generated UUID: " + uuid.toString());
    }
}

If you need to generate a specific UUID version, you need to use a third-party library such as uuid-creator which offers more flexible options:



//generate UUID version 1
UUID uuid = UuidCreator.getTimeBased();

//generate UUID version 2
UUID uuid = UuidCreator.getDceSecurity(UuidLocalDomain.LOCAL_DOMAIN_PERSON, 1234);

//generate UUID version 3
UUID uuid = UuidCreator.getNameBasedMd5(UuidNamespace.NAMESPACE_URL, "https://github.com/");

//generate UUID version 4
UUID uuid = UuidCreator.getRandomBased();

//generate UUID version 5
UUID uuid = UuidCreator.getNameBasedSha1(UuidNamespace.NAMESPACE_URL, "https://github.com/");

//generate UUID version 6
UUID uuid = UuidCreator.getTimeOrdered();

//generate UUID version 7
UUID uuid = UuidCreator.getTimeOrderedEpoch();

How do I generate UUID in...

Find out how to generate UUIDs in your favorite language here: Bash, Groovy, Kotlin, Python, Scala, Clojure, ClojureScript, JavaScript, or return to Online UUID Generator