How to Generate UUIDs in Java

In Java, you can generate universally unique identifiers (UUIDs) using the java.util.UUID class. Here’s how you can generate a UUID:

Example Code

package org.kodejava.util;

import java.util.UUID;

public class UUIDExample {
    public static void main(String[] args) {
        // Generate a random UUID
        UUID uuid = UUID.randomUUID();
        System.out.println("Generated UUID: " + uuid.toString());
    }
}

Explanation

  • The UUID.randomUUID() method generates a type-4 (pseudo-random) UUID.
  • The output will look something like: f47ac10b-58cc-4372-a567-0e02b2c3d479.
  • The toString() method converts the UUID object into its string representation.

Other UUID Options

If you want to specify your own inputs, you can use the UUID.fromString(String uuid) or create a UUID from specific values with UUID.nameUUIDFromBytes(byte[] bytes). For example:

package org.kodejava.util;

import java.util.UUID;

public class UUIDFromNameExample {
    public static void main(String[] args) {
        // Generate a UUID based on an input name
        UUID uuid = UUID.nameUUIDFromBytes("example.com".getBytes());
        System.out.println("Generated UUID from name: " + uuid.toString());
    }
}

Notes

  • UUIDs are useful for generating unique IDs in distributed systems, database keys, and more.
  • Version-4 (random) UUIDs are the most commonly used since they rely only on randomness and are highly unlikely to collide.

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