Generating UUID in Java

Java

UUID stands for Universally Unique Identifier. It is a unique identifier with 128-bit number string (RFC 4122). It represented in 32 Hexadecimal characters and mixed with 4 dash - characters.

UUID also known as GUID which stands for Globally Unique Identifier.

In software development, UUID can be generated and used it as:

  • Session ID in web application
  • Primary key in database’s table
  • Transaction ID
  • Random filename creation

In this tutorial, we’ll show you few examples of how to generate UUID in Java.

What You’ll Need

  • Oracle JDK 1.6 or above
  • Java UUID Generator 3.1.4

Example 1: java.util.UUID

Use JDK java.util.UUID class to generate version 4 UUID which is randomly generated UUID.

Example code:

GenerateUUIDExample.java

import java.util.UUID;

public class GenerateUUIDExample {

    public static void main(String[] args) {

        // Generate version 4 UUID - Randomly generated UUID
        UUID uuid = UUID.randomUUID();

        System.out.println("Generated UUID: " + uuid.toString());
        System.out.println("UUID version  : " + uuid.version());
        System.out.println("UUID variant  : " + uuid.variant());

    }

}

Output:

Generated UUID: 3642d408-92e5-42fa-a32a-b4ff0a878eb9
UUID version  : 4
UUID variant  : 2

Example 2: Java UUID Generator

Use Java UUID Generator (JUG) to generate UUID. This is the example of version 1 UUID and version 4 UUID generation.

Maven dependency:

<dependency>
   <groupId>com.fasterxml.uuid</groupId>
   <artifactId>java-uuid-generator</artifactId>
   <version>3.1.4</version>
</dependency>

Example code:

JugUUIDExample.java

import java.util.UUID;

import com.fasterxml.uuid.Generators;

public class JugUUIDExample {

    public static void main(String[] args) {

        // Generate version 1 UUID - Time-based UUID
        UUID uuid2 = Generators.timeBasedGenerator().generate();

        System.out.println("Generated version 1 UUID: " + uuid2.toString());
        System.out.println("Version 1 UUID version  : " + uuid2.version());
        System.out.println("Version 1 UUID variant  : " + uuid2.variant());

        // Generate version 4 UUID - Randomly generated UUID
        UUID uuid1 = Generators.randomBasedGenerator().generate();

        System.out.println("Generated version 4 UUID: " + uuid1.toString());
        System.out.println("version 4 UUID version  : " + uuid1.version());
        System.out.println("version 4 UUID variant  : " + uuid1.variant());

    }

}

Output:

Generated version 1 UUID: 8d443d10-2ebf-11e7-a09a-1d5a93496478
Version 1 UUID version  : 1
Version 1 UUID variant  : 2
Generated version 4 UUID: adfabcb7-6fc5-42c8-babc-b76fc532c8dc
version 4 UUID version  : 4
version 4 UUID variant  : 2

Summary

In this tutorial, we have shown you several examples of generating UUID in Java.

Other Resources