How To Generate UUID In Java

In this example we are generating UUID using java API. We can use this java API if your JDK is above 1.5.

Following are the important methods avaialbe on UUID class

Note String toString(), This method will returns a String object representing this UUID.
int variant(), This method will returns the variant number associated with this UUID.
int version(), This method will returns the version number associated with this UUID.

Reference ->

Usage of java.util.UUID class

This class is used to generate random UUID (Universally unique identifier).

It is first introduced with JDK 1.5, method randomUUID() will return a UUID object, we need to convert this UUID object to string in order to use this.

Code to Generate UUID In Java

package com.test;

import java.util.UUID;

public class GenerateJavaUUIDExample {

     * How To Generate UUID (Universally unique identifier) In Java
public static void main(String[] args) {
UUID first = UUID.randomUUID();
        UUID second = UUID.randomUUID
("UUID first: " + first);
("UUID second: " + second);
("UUID version: " + second.version());
("UUID variant: " + second.variant());
UUID first: 6a2871ee-3cba-4074-9fa4-68d2a8312291
UUID second: 5f8b876c-87b4-4f83-8fea-f9a761552ed4
UUID version: 4
UUID variant: 2


Your email address will not be published. Required fields are marked *