Open In App

How to Convert a String to a UUID in Java?

A Universally Unique Identifier (UUID) is a 128-bit label utilised for information in computer systems. The term Globally Unique Identifier (GUID) is also used especially in Microsoft systems. UUIDs are regularised by the Open Software Foundation (OSF) as part of the Distributed Computing Environment (DCE). When generated according to the standard methods, UUIDs are usually unique(mostly). In this article, we will see how to Convert a String to a UUID in Java.

Generating UUID

The Code below shows how to generate a UUID:

import java.util.UUID;

class GenerateUuid {
    public static void main (String[] args) {
      UUID uuid = UUID.randomUUID();
      String uuidAsString = uuid.toString();
      
      System.out.println("Your UUID as String is:- "+ uuidAsString);
    }
}

Output
Your UUID as String is:- 80412d77-5abb-4893-ac56-a2de12e7931c




Converting String to UUID

Although it is very much less likely to be used but in some circumstances UUID are required to be converted in Strings. Java allows this convertion using the static fromString(String) method.

Syntax:

public static UUID fromString(String UUID_name)

The below code shows the conversion:

import java.util.UUID;

class MyUuidApp {
    public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        String uuidAsString = uuid.toString();

        UUID Uuid = UUID.fromString(uuidAsString);
        
        System.out.println("The UUID for the given string is : "+ Uuid);
    }
}

Output
The UUID for the given string is : 4731e9e0-c627-43f9-808a-7e8637abb912




Article Tags :