Convert UUID to String in Java

Introduction

In this article, we will have a look on How to Convert UUID to String in Java. We will also shed some light on the concept of UUID, its use, and its corresponding representation in Java class. Let us have a quick look at UUID.

UUID: UUID stands for Universally Unique Identifier which identifies a unique entity or resource in the computer systems. This resource can be a document, real-time object, file, and more. It is also known by the name GUID or Globally Unique Identifier for its extensive use.

It is a value of size 128 bits composed of 32 hexadecimal-based characters and 6 ‘-‘ i.e. hyphens that account for its total length of 36 characters. In programming, we generally represent this type of data as a String.

Example of a UUID: 123e4567-e89b-12d3-a456-426614174000

UUID follows universal standards set by the Internet Society to ensure the uniqueness of every resource that has a UUID.

Uses:

  • The Uniqueness of UUIDs makes them useful for being Associative keys in database tables.
  • They are also used as Identifiers for physical hardware within an organization.
  • They have applications in Cryptography and other hashing utilities.

UUID class in Java

With the advent of Java 7, the UUID class was introduced in Java which packed the different specifications and utilities of UUID into a single unit with some useful methods as well.

We can generate a random UUID or we can generate the UUID from an input String as well. We can generate it as a UUID object or convert it to a string as well. If we can convert a UUID to a String, then we can format and perform the same operations with the utility methods that are possible on a String.

Let us look at how we can generate UUIDs and print them:

Output:

Convert UUID to String in Java

We can print a UUID object directly or use the String representation of the UUID object. With the toString() method we can convert a UUID to its equivalent String representation. We can change the object type but the representation remains the same.

We will discuss two different examples where we generate a random UUID and another from a given string. Then we convert them to String using the toString() method.

Let us look at the code snippet for the two approaches.

Output:

Next, In the below example, we generate UUID from an input string using the fromString() method of the UUID class.

Output:

That’s all for the article, we had a brief look at the UUID’s concept, and a brief look at its Java class. Along with this, we had a look at How to Convert a UUID to a String and its representation. You can try out the above examples in your local Java compiler/IDE.

Feel free to reach out to us for any suggestions/doubts.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *