A UUID (Universally Unique Identifier) is a 128-bit identifier that is globally unique. It is often used to uniquely identify resources across different systems. In Java, the java.util.UUID class provides various methods to generate UUIDs.
The java.util.UUID class provides a randomUUID()
method that generates a random UUID. Here's an
example:
import java.util.UUID; public class UUIDGenerator { public static void main(String[] args) { UUID uuid = UUID.randomUUID(); System.out.println("Generated UUID: " + uuid.toString()); } }
Another way to generate UUIDs in Java is by using the java.util.Random
class. Here's an example:
import java.util.Random; public class UUIDGenerator { public static void main(String[] args) { Random random = new Random(); long mostSignificantBits = random.nextLong(); long leastSignificantBits = random.nextLong(); UUID uuid = new UUID(mostSignificantBits, leastSignificantBits); System.out.println("Generated UUID: " + uuid.toString()); } }
Apache Commons provides a library called "commons-lang" which includes a RandomStringUtils
class that can be used to generate UUIDs. Here's an example:
import org.apache.commons.lang3.RandomStringUtils; public class UUIDGenerator { public static void main(String[] args) { String uuid = RandomStringUtils.random(32, true, true); System.out.println("Generated UUID: " + uuid); } }
In this tutorial, we discussed different ways to generate UUIDs in Java. We explored the java.util.UUID
class, the java.util.Random
class, and the Apache Commons library. You can choose the method that
best suits your requirements and use it to generate unique identifiers for your applications.