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:
- import java.util.UUID;
- public class CreateGuid {
- public static void main(String[] args) {
- UUID uuid = UUID.randomUUID();
- System.out.println("UUID = " + uuid.toString());
- }
- }
Explanation
- Line #1 imports the UUID class from the java.util package so that it can be used in the code.
- Line #2 defines a new class named CreateGuid.
- Line #3 defines the main method, which is the entry point of the program.
- Line #4 creates a new variable named uuid of type UUID and assigns it a new randomly generated UUID by calling the static method randomUUID() of the UUID class.
- Line #5 prints the string "UUID = " followed by the string representation of the uuid variable to the standard output stream.
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.
- import java.util.UUID;
- public class StringToUUID {
- public static void main(String[] args) {
- String uuidString = "6e48fa2a-27c0-48c7-9d20-83aa99f23cee";
- UUID uuid = UUID.fromString(uuidString);
- System.out.println(uuid);
- }
- }
Explanation
- Line #1 imports the UUID class from the java.util package. This class provides static factory methods for creating and working with UUIDs.
- Line #2 defines a new public class named StringToUUID. This is the class that contains our program.
- Line #3 defines the main method of our program. This is the entry point of our program and is where the execution of our program begins.
- Line #4 defines a new string variable named uuidString and assigns it the value "123e4567-e89b-12d3-a456-426614174000". This is a string representation of a UUID.
- Line #5 uses the fromString method of the UUID class to convert the string representation of the UUID into a UUID object. The fromString method takes a single argument: the string representation of the UUID. The result of this method call is assigned to a new variable named uuid.
- Line #6 prints out the resulting UUID object using the System.out.println method. This will print out the string representation of the UUID to the standard output stream.