← Back to Chapters

UUID in Java

? UUID in Java

? Quick Overview

UUID (Universally Unique Identifier) is a 128-bit value used to uniquely identify information across systems. In Advanced Java, UUIDs are commonly used for database primary keys, distributed systems, session identifiers, and API tokens.

? Key Concepts

  • UUID is defined in java.util.UUID
  • Guarantees very high uniqueness
  • Does not depend on a central authority
  • Safe for distributed and concurrent systems

? Syntax / Theory

A UUID is represented as a 36-character string (32 hex digits + 4 hyphens). Java provides built-in methods to generate and parse UUID values.

? Code Example(s)

? View Code Example
// Generating a random UUID using Java
import java.util.UUID;

public class UUIDExample {
public static void main(String[] args) {
UUID uuid = UUID.randomUUID();
System.out.println(uuid);
}
}
? View Code Example
// Converting UUID to String and back to UUID
import java.util.UUID;

public class UUIDConversion {
public static void main(String[] args) {
UUID original = UUID.randomUUID();
String uuidStr = original.toString();
UUID parsed = UUID.fromString(uuidStr);
System.out.println(parsed);
}
}

? Interactive Generator

Click below to simulate Java's UUID.randomUUID() behavior right now!

Click Generate to Start

? Live Output / Explanation

Output

Each execution prints a different value like:
f47ac10b-58cc-4372-a567-0e02b2c3d479

This proves that UUIDs are randomly generated and extremely unlikely to collide.

✅ Tips & Best Practices

  • Use UUIDs for distributed databases instead of auto-increment IDs
  • Store UUIDs as CHAR(36) or BINARY(16) in databases
  • Avoid exposing sequential IDs in public APIs
  • Prefer UUID over Random numbers for identifiers

? Try It Yourself

  • Generate 5 UUIDs and check if any duplicates appear
  • Store UUIDs in a database table as primary keys
  • Create a REST API that returns a UUID per request
  • Compare UUID with auto-increment IDs in performance