Search code examples
javauuid

How to create Unique Id in Java


I have a code like below:

D00077B4-EBFB-4BD8-9E3F-1F3943CBCE35

I was wondering how I could generate a code like this in Java.


Solution

  • This is a UUID, "a 128-bit number used to identify information in computer systems".

    The format is explained as:

    In its canonical textual representation, the sixteen octets of a UUID are represented as 32 hexadecimal (base 16) digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens). For example:

    123e4567-e89b-12d3-a456-426655440000
    xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
    

    How to generate the code like this using Java?

    // Create a random UUID:
    UUID uuid1 = UUID.randomUUID();
    System.out.println(uuid1);
    
    // Create a fixed UUID:
    String uuidString = "D00077B4-EBFB-4BD8-9E3F-1F3943CBCE35";
    UUID uuid2 = UUID.fromString(uuidString);
    System.out.println(uuid2);
    
    // Get string from UUID:
    UUID uuid = ...
    String s = uuid.toString();
    System.out.println(s);