Generate Unique id using UUID in java

Java provides a class java.util.UUID which can be used to generate a randon UUID. Here is a sample code to create a UUID.

UUID randomUUID = UUID.randomUUID();

System.out.println(randomUUID.toString());

Output:

 e617f74f-d0cd-4f17-988f-5a05a94ac63e

So the above code can be used to assign ids to entities e.g;

Suppose you are writing Person java class and want each person to have a unique id, you can use UUID to create a unique id for each person object.

class Person {

   private UUID personUUID;

   private String name;

   private String  phoneNumber;

 // here are getters and setters
}

public Person createPerson(){
   Person person = new Person();
   person.setPersonUUID(UUID.randomUUID());
   person.setName("Obama");
   return person;
}
Like this post? Don’t forget to share it!

Leave a Reply

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