How do I generate UUID / GUID?

Category: java.util, viewed: 6576 time(s).

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 org.kodejava.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
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats