java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to generate UUID / GUID?

UUID / GUID (Universally / Globally Unique IDentifier) are 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

package com.javacoderanch.example.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 = 7dc53df5-703e-49b3-8670-b1c468f47f1f
UUID version       = 4
UUID variant       = 2