How do I generate UUID / GUID in Java?

UUID / GUID (Universally / Globally Unique Identifier) is frequently use in programming. Some of its usage are for creating random file names, session id in web application, transaction id and for record’s primary keys in database replacing the sequence or auto generated number.

To generate UUID in Java we can use the java.util.UUID class. This class was introduced in JDK 1.5. The UUID.randomUUID() method return a UUID object. To obtain the value of the random string generated we need to call the UUID.toString() method.

We can also get the version and the variant of the UUID using the version() method and variant() method respectively. Let’s see the code snippet below:

package org.kodejava.util;

import java.util.UUID;

public class RandomStringUUID {
    public static void main(String[] args) {
        // Creating a random UUID (Universally unique identifier).
        UUID uuid = UUID.randomUUID();
        String randomUUIDString = uuid.toString();

        System.out.println("Random UUID String = " + randomUUIDString);
        System.out.println("UUID version       = " + uuid.version());
        System.out.println("UUID variant       = " + uuid.variant());
    }
}

The result of our program is:

Random UUID String = 87a20cdd-25da-4dc2-b787-68054ec2c5ca
UUID version       = 4
UUID variant       = 2