UUID Class in Java
The UUID class in Java, in java.util, represents a universally unique identifier: a 128-bit value that is practically guaranteed to be different from every other UUID ever created, without any central list or database. It is used for IDs of orders, files, sessions and database rows, especially when IDs are created on many machines at once. A UUID is written as 36 characters, such as 3f2b8c1e-7d4a-4b6e-9a1f-2c5d8e9f0a1b. In this lesson, you will learn how to create and use UUIDs.
Declaration
public final class UUID implements Serializable, Comparable<UUID>Methods of UUID
| Method | Description |
|---|---|
static UUID randomUUID() | It is used to create a random (version 4) UUID. |
static UUID nameUUIDFromBytes(byte[] name) | It creates the same (version 3) UUID every time for the same name. |
static UUID fromString(String s) | It parses a UUID from its 36-character text. |
String toString() | It returns the 36-character text form. |
int version() | It returns the version: 4 for random, 3 for name-based. |
long getMostSignificantBits() / getLeastSignificantBits() | It returns the two 64-bit halves. |
Example: Random UUIDs
Let's see an example that creates random IDs for orders. Random UUIDs differ on every run, so the output is a sample.
import java.util.UUID;
public class RandomIds {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
UUID id = UUID.randomUUID();
System.out.println("Order " + i + ": " + id);
}
UUID one = UUID.randomUUID();
System.out.println("Length: " + one.toString().length()
+ ", version: " + one.version());
}
}Order 1: 95535e6f-612f-41c7-8863-927e7c8d1147
Order 2: 82bb4141-1c73-43f5-bfa0-259214d45ec7
Order 3: 88a17b06-9062-4eae-a0ac-cd20e1ec3c09
Length: 36, version: 4Explanation: randomUUID uses a secure random generator to fill 122 of the 128 bits, so two UUIDs are almost impossible to repeat. The 13th character is always 4, the version number.
Example: Name-Based and Parsed UUIDs
import java.nio.charset.StandardCharsets;
import java.util.UUID;
public class NameIds {
public static void main(String[] args) {
byte[] name = "navika@mail.com".getBytes(StandardCharsets.UTF_8);
UUID a = UUID.nameUUIDFromBytes(name);
UUID b = UUID.nameUUIDFromBytes(name);
System.out.println(a);
System.out.println("Same each time? " + a.equals(b)
+ ", version " + a.version());
UUID parsed = UUID.fromString(a.toString());
System.out.println("Parsed equals original? " + parsed.equals(a));
try {
UUID.fromString("not-a-uuid");
} catch (IllegalArgumentException e) {
System.out.println("Invalid: " + e.getMessage());
}
}
}e9d792f1-e531-32ad-986c-04859ea2c0cf
Same each time? true, version 3
Parsed equals original? true
Invalid: Invalid UUID string: not-a-uuidExplanation: nameUUIDFromBytes turns the same input into the same UUID every time, which is useful for stable IDs derived from a name. fromString reads a UUID back from text, and rejects text in the wrong format.
Common Mistakes
Comparing UUIDs with ==. Use equals.
Storing UUIDs as text in large databases without thought. 36 characters take more space than the 16 bytes a UUID really needs; many databases have a UUID column type.
Expecting random UUIDs to be sorted by creation time. Version 4 UUIDs are random; ordering by them gives a random order.
Practice
- Easy: Create five random UUIDs and store them in a
HashSet. Print the size of the set. - Harder: Write a method that turns an email address into a stable customer ID with
nameUUIDFromBytes, ignoring upper and lower case differences.
Key Takeaways
Was this tutorial helpful?