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;
}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.