In this article, we will see,
- What is UUID?
- Java UUID class
What is UUID?
UUID, a universally unique identifier is a 128-bit number used to identify information in computer systems.
UUID is made of hex digits along with 4 hyphen (“-“) symbols. The length of a UUID is 36 characters.
There are 4 types of UUID
- Time-based UUID (Version 1)
- DCE Security UUID (Version 2)
- Name-based UUID (Version 3 and 5)
- Randomly Generated UUID (Version 4)
Mostly Randomly Generated UUID i.e. UUID Version 4 is used.
UUID Version 4 uses random numbers as a source. It uses an unpredictable value as the seed to generate random numbers to reduce the chance of collisions
There are 4 types of UUID variant
- 0: It is reserved for NCS backward compatibility
- 2: Leach-Salz
- 6: It is reserved for Microsoft backward compatibility
- 7: It is reserved for future definition.
Mostly variant 2 is used.
UUID can be used in the following cases
- As a primary key of the database table
- To create a session ID for a web application
- To represent as transaction ID
- To create a random file name
Example UUID
df6fdea1-10c3-474c-ae62-e63def80de0b
Java UUID class
UUID Class belongs to the java.util
package. It represents an immutable universally unique identifier (UUID).
UUID Constructor
`[UUID](https://docs.oracle.com/javase/8/docs/api/java/util/UUID.html#UUID-long-long-)(long mostSigBits, long leastSigBits)`
Constructs a new UUID
using the specified data.
Static methods
There are three static methods of a UUID class,
UUID.fromString(String name)
The above method creates a UUID from the string standard representation as described in the toString() method.
UUID.nameUUIDFromBytes(byte[] name)
This method is used to create a version 3 (name-based) UUID based on the specified byte array.
UUID.randomUUID()
This method is used to create a version 4 (pseudo-randomly generated) UUID.
Instance methods
Also, there are a few instance methods of a UUID class.
clockSequence()
This method is used to get the clock sequence value associated with this UUID.
This method returns the clock sequence value as int
.
compareTo(UUID val)
This method is used to compare this UUID with the specified UUID ( the one received as method param i.e. val
This method returns -1, 0 or 1 as this UUID
is less than, equal to, or greater than val
equals(Object obj)
This method simply compares this object to the specified object. It returns the result in boolean
node()
This method returns the node value (long
) associated with this UUID.
timestamp()
This method returns the timestamp value (long
) associated with this UUID.
toString()
This method returns a String
object representing this UUID.
variant()
This method returns the variant number (int
) associated with this UUID.
version()
This method returns the version number (int
) associated with this UUID.
You can visit my YouTube channel ‘coderolls’ to find more video tutorials.