How to generate a UUID in Java

Java is a popular programming language that is used to develop a wide range of applications, including mobile apps, web apps, desktop apps, and games 1. It is known for its “write once, run anywhere” capability, meaning that Java code can be written once and run on any device that has a Java Virtual Machine (JVM) installed.

Here is an example of how to generate a UUID in Java:

  1. import java.util.UUID;
  2. public class CreateGuid {
  3.     public static void main(String[] args) {
  4.         UUID uuid = UUID.randomUUID();
  5.         System.out.println("UUID = " + uuid.toString());
  6.     }
  7. }


How to convert from a string to UUID in Java

This program uses the fromString method of the UUID class to convert a string representation of a UUID into a UUID object. The string must be in the format specified by the toString method of the UUID class.

  1. import java.util.UUID;
  2. public class StringToUUID {
  3.     public static void main(String[] args) {
  4.         String uuidString = "6e48fa2a-27c0-48c7-9d20-83aa99f23cee";
  5.         UUID uuid = UUID.fromString(uuidString);
  6.         System.out.println(uuid);
  7.     }
  8. }