Generating an Alphanumeric UUID String in Java

06 May 2023 Balmiki Mandal 0 Core Java

Generating an Alphanumeric UUID String in Java

A Universally Unique Identifier (UUID) is a 128-bit number used to identify computer objects such as files, services, and accounts. In Java, UUIDs are generated using the java.util.UUID class. The UUIDs generated by this class are composed of lowercase hexadecimal digits (0-9 and a-f). In some cases, it might be useful to generate an alphanumeric UUID, which includes both uppercase and lowercase letters as well as numbers. In this article, we'll look at how to generate an alphanumeric UUID string in Java.

Generating an Alphanumeric UUID String in Java

The most straightforward way to generate an alphanumeric UUID string in Java is to use the java.util.UUID class. This class has a static method called randomUUID(), which generates a type 4 (randomly generated) UUID:

    String uuidString = UUID.randomUUID().toString();

The above code will generate a random UUID string that looks something like this: e59dyt45-d7c2-4fde-a5fe-c5f7g117471e. As we can see, this UUID string consists of lowercase hexadecimal digits only.

To generate an alphanumeric UUID string, we must first convert the UUID to its byte representation and then convert the byte array to a Base64 string. Here's an example of how to do this:

    UUID uuid = UUID.randomUUID();
    byte[] bytes = new byte[16];
    ByteBuffer.wrap(bytes).putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits());
    String alphanumericUuidString = Base64.getEncoder().encodeToString(bytes);

The above code will generate a string consisting of both uppercase and lowercase letters as well as numbers that looks something like this: B1tIzcGjuggXF0KOOOiYWQ.

Conclusion

In this article, we looked at how to generate an alphanumeric UUID string in Java. We saw how to convert a random UUID to its byte representation and then convert the byte array to a Base64 string. With this method, we can generate a string consisting of both uppercase and lowercase letters as well as numbers.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.