How to Generate an unique ID in Java

Example

UUID is the fastest and easiest way to generate unique ID in Java.


import java.util.UUID;  
public class UniqueIDTest {  
 public static void main(String[] args) {  
  UUID uniqueKey = UUID.randomUUID();   
  System.out.println (uniqueKey);  
}  
}  

Result


0a6a3de7-b974-42d0-af9e-9c23473b09b9

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

10 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Aashwinee
8 years ago

Hi, what if we want to generate unique ID with fixed length then how the code looks like.

Amol
13 years ago

I am trying to generate a unique 10 digit alpha numeric number, any way to do that in a distributed system

varsha janghu
7 years ago

good tutorials

Erik Boisen
8 years ago

Is there any way to get a unique id that will be the same every time for a particular machine regardless of OS?

André Verwijs
9 years ago

is this version 1 or version 4 uuid..??

lucky_muzhik
11 years ago

Thank you. in the bull’s eye

sam009
12 years ago

Nice piece of code but not every time it is unique….

sudheer
12 years ago

its good,thanks

Anil
14 years ago

Its Good, simple way to get UUID

Karthikeyan
16 years ago

Its nice. Could have explored the options supported in UUID and the limitations identified to explore more.