Java UUID randomUUID()

In this guide, you will learn about the UUID randomUUID() method in Java programming and how to use it with an example.

1. UUID randomUUID() Method Overview

Definition:

The randomUUID() method of the UUID class in Java is a static method that generates a random universally unique identifier (UUID). A UUID represents a 128-bit value, and the randomUUID() method uses a cryptographically strong pseudo-random number generator to generate the UUID.

Syntax:

public static UUID randomUUID()

Parameters:

The method does not take any parameters.

Key Points:

- The UUID class is part of the java.util package.

- The randomUUID() method generates a random UUID using a pseudo-random number generator.

- The generated UUID is of type 4, as per the UUID specifications.

- The method is thread-safe and can be used to generate unique identifiers in a multi-threaded environment.

- Each call to randomUUID() generates a completely new and unique value.

2. UUID randomUUID() Method Example

import java.util.UUID;

public class UUIDExample {
    public static void main(String[] args) {
        // Generating and printing random UUIDs
        UUID uuid1 = UUID.randomUUID();
        System.out.println("First Random UUID: " + uuid1);

        UUID uuid2 = UUID.randomUUID();
        System.out.println("Second Random UUID: " + uuid2);

        // Demonstrating that generated UUIDs are unique
        System.out.println("Are the two UUIDs equal? " + uuid1.equals(uuid2));
    }
}

Output:

First Random UUID: f47ac10b-58cc-4372-a567-0e02b2c3d479
Second Random UUID: e2f99e1f-7ffb-4b42-9e11-2ff7fdb12345
Are the two UUIDs equal? false

Explanation:

In this example, we called the randomUUID() method twice to generate two different random UUIDs and printed them out. As the method generates unique values each time it is called, the two UUIDs are not equal, demonstrating the uniqueness of the generated UUIDs.

Comments