The UUID Class
The java.util.UUID class represents an immutable Universally Unique Identifier (UUID).
A UUID represents a 128-bit value that is unique across both space and time. They are incredibly useful when you need to generate a unique key without coordinating with a central authority (like an auto-incrementing database column).
What does a UUID look like?
A UUID is typically represented as a 36-character string consisting of 32 hexadecimal digits and 4 hyphens.
Example: 550e8400-e29b-41d4-a716-446655440000
Common Use Cases
- Primary Keys: Generating unique IDs for database records in distributed systems.
- Session IDs: Generating unique tokens for user sessions in web applications.
- Transaction IDs: Tracking unique requests across microservices.
- File Names: Preventing naming collisions when uploading files.
Generating a UUID
The most common way to generate a UUID in Java is by using the static method UUID.randomUUID(). This generates a Type 4 (pseudo-randomly generated) UUID.
import java.util.UUID;
public class LabUUID1 {
public static void main(String[] args) {
// Generate a random UUID
UUID uniqueKey = UUID.randomUUID();
// Print the UUID as a String
System.out.println("Generated UUID: " + uniqueKey.toString());
}
}
Output:
Generated UUID: 123e4567-e89b-12d3-a456-426614174000
[!TIP] The chance of a collision (generating the exact same UUID twice) using
UUID.randomUUID()is so astronomically small that it is considered practically zero. You do not need to check a database to ensure the ID is unique before using it!