UUID / GUID (Universally / Globally Unique Identifier)
is frequently use in programming. Some of its usage are for creating random file names, session id in web application, transaction id and for record’s primary keys in database replacing the sequence or auto generated number.
To generate UUID in Java we can use the java.util.UUID
class. This class was introduced in JDK 1.5. The UUID.randomUUID()
method return a UUID object. To obtain the value of the random string generated we need to call the UUID.toString()
method.
We can also get the version and the variant of the UUID using the version()
method and variant()
method respectively. Let’s see the code snippet below:
package org.kodejava.util;
import java.util.UUID;
public class RandomStringUUID {
public static void main(String[] args) {
// Creating a random UUID (Universally unique identifier).
UUID uuid = UUID.randomUUID();
String randomUUIDString = uuid.toString();
System.out.println("Random UUID String = " + randomUUIDString);
System.out.println("UUID version = " + uuid.version());
System.out.println("UUID variant = " + uuid.variant());
}
}
The result of our program is:
Random UUID String = 87a20cdd-25da-4dc2-b787-68054ec2c5ca
UUID version = 4
UUID variant = 2
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024