What is UUID ?
I have come across the usage of UUID in various areas of my projects, which has piqued my curiosity to gain a deeper understanding of it.
UUID stands for ‘Universally Unique Identifier’. It is a class found in the java.util package and is utilized to create unique identifiers.
UUIDs are commonly needed in distributed environments where we need to generate unique keys that do not overlap with each other.
A UUID is a 128-bit value that is expressed as a hexadecimal string, usually divided into groups using hyphens (-)
|
|
The “V” indicates the version of the UUID format, and the “N” indicates the variant.
|
|
Common use cases for UUID:
- UUID is widely used to generate primary key of the entity classes
- To uniquely identify a transaction or business flow id in distributed systems
- To generate unique identifiers for session and cookies in web applications
- To generate random data for multiple test cases
How to generate UUID programmatically in Java?
UUID is a class that represents an immutable universally unique identifier (UUID).
A UUID represents a 128-bit value.
To get UUID we need to call static factory method randomUUID.
The UUID is generated using a cryptographically strong pseudo random number generator.
|
|
Output is:
|
|
Getting UUID based on string
Creates a UUID from the string standard representation as described in the toString method.
|
|
Output:
|
|
Getting UUID from bytes
We can also create UUID from bytes by calling nameUUIDFromBytes method.
|
|
|
|
Comparing 2 UUID’s
We can compare 2 UUID’s by calling compareTo() method.
|
|
|
|
Thus with the above examples we have seen that UUIDs ensures an identifier will be unique across different systems and over time.