Wednesday 7 January 2015

Generate universal unique identifiers in Java


A universally unique identifier (UUID) is an identifier standard used in software construction. A UUID is simply a 128-bit value. The meaning of each bit is defined by any of several variants.

For human-readable display, many systems use a canonical format using hexadecimal text with inserted hyphen characters.

For example:
510c7b5b-a8c1-454a-be90-9904a97ab780

Java provides UUID class to generate Universal unique identifiers.

UUID class provides below static methods to generate unique ids.

public static UUID fromString(String name)
Creates a UUID from the string standard representation.

public static UUID nameUUIDFromBytes(byte[] name)
Creates UUID from given byte array as input.

public static UUID randomUUID()
The UUID is generated using a cryptographically strong pseudo random number generator.

import java.util.UUID;

public class UniqueIdGenerator {
    
    public static void main(String args[]){
        byte arr[] = {1,2,3,4,5};
        System.out.println(UUID.randomUUID());
        System.out.println(UUID.fromString("c25cccab-59bd-434a-a31b-0f15f8d420b1"));
        System.out.println(UUID.nameUUIDFromBytes(arr));
    }
}


Output
9bf67a08-2c7b-4171-818e-996ad3d93b9f
c25cccab-59bd-434a-a31b-0f15f8d420b1
7cfdd078-89b3-395d-aa55-0914ab35e068

No comments:

Post a Comment