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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.