Java UUID Generator – Java GUID

Filed Under: Java

Java UUID

Java UUID (Universally Unique Identifier) class is part of java.util package. Java UUID class represents an immutable universally unique identifier and represents 128-bit value. It is also known as GUID (Globally Unique Identifier).

java uuid, java guid

Java UUID Usage

Java UUID is used to create following:

  • Random File Name
  • Session Id for Java Web Application
  • Primary Key for Database Table
  • Transaction Id

Java UUID Constructor


public UUID(long  mostSigBits,  long  leastSigBits)

Creates a new UUID using specified data.

UUID Version & Variants

There are different variants of UUID but mostly we will see variant 2 (Leach-Salz) in our examples.
java uuid version variant

UUID variants:

  1. 0 – Reserved for NCS backward compatibility
  2. 2 – Leach-Salz
  3. 6 – Reserved, Microsoft Corporation backward compatibility
  4. 7 – Reserved for future definition

UUID Versions:

  1. time-based(version 1)
  2. DCE Security(version 2)
  3. name-based(version 3)
  4. randomly generated UUID(version 4)

Java UUID Generator

We can use java-uuid-generator maven dependency for generating UUID. You can include that using below maven dependency.


<dependency>
    <groupId>com.fasterxml.uuid</groupId>
    <artifactId>java-uuid-generator</artifactId>
    <version>3.1.4</version>
</dependency>

Let’s have a look at the below java uuid generator example program.


package com.journaldev.examples;

import java.util.UUID;

import com.fasterxml.uuid.Generators;

/**
 * Java UUID Generator
 *
 */
public class UUIDVersionExample {

	public static void main(String[] args) {
		
		//Generate time-based UUID
		UUID uuid1 = Generators.timeBasedGenerator().generate();
		System.out.println("UUID : "+uuid1);
		System.out.println("UUID Version : "+uuid1.version());
		System.out.println("UUID Variant : "+uuid1.variant());
		
		//Generate random UUID
		UUID uuid2 = Generators.randomBasedGenerator().generate();
		System.out.println("UUID : "+uuid2);
		System.out.println("UUID Version : "+uuid2.version());
		System.out.println("UUID Variant : "+uuid2.variant());
	}

}

Output of the above uuid generator program is below:


UUID : 5fc03087-d265-11e7-b8c6-83e29cd24f4c
UUID Version : 1
UUID Variant : 2
UUID : e8e3db08-dc39-48ea-a3db-08dc3958eafb
UUID Version : 4
UUID Variant : 2

Java UUID Methods

Let’s have a look at the below UUID methods with example program.

  1. randomUUID(): This is a static factory method to fetch type 4 random UUID.
  2. 
    package com.journaldev.examples;
    
    import java.util.UUID;
    /**
     * Java UUID randomUUID Example
     *
     */
    public class UUIDExample {
    
    	public static void main(String[] args) {
    		//initialize uuid
    		UUID uuid = UUID.randomUUID();
    		System.out.println(uuid);
    
    	}
    
    }
    

    Output of the above program is below:

    
    84cff9ea-de0f-4841-8645-58620adf49b2
    
  3. fromString(String name): This method creates UUID from specified string. This is useful when you have to convert string to UUID object.
  4. 
    package com.journaldev.examples;
    
    import java.util.UUID;
    /**
     * Java UUID fromString Example
     *
     */
    public class UUIDExample {
    
    	public static void main(String[] args) {
    		//initialize uuid
    		UUID uuid = UUID.fromString("84cff9ea-de0f-4841-8645-58620adf49b2");
    		System.out.println(uuid);
    
    	}
    
    }
    
  5. clockSequence(): This method returns clock sequence associated with UUID and to fetch clock sequence we need to create time-based (version 1) UUID otherwise it will throw UnsupportedOperationException.
  6. 
    package com.journaldev.examples;
    
    import java.util.UUID;
    
    import com.fasterxml.uuid.Generators;
    
    /**
     * Java UUID Clock Sequence Program
     *
     */
    public class UUIDClockSequenceExample {
    
    	public static void main(String[] args) {
    		// Generate time-based UUID
    		UUID uuid = Generators.timeBasedGenerator().generate();
    		System.out.println("UUID : " + uuid);
    		System.out.println("UUID Clock Sequence : "+uuid.clockSequence());
    	}
    }
    

    Output of the above program is below:

    
    UUID : 52334bd0-d266-11e7-a11d-0148035fb8f1
    
    UUID Clock Sequence : 8477
    
  7. getLeastSignificantBits(): This method returns least significant 64 bits of UUID.
  8. getMostSignificantBits(): This method returns most significant 64 bits of UUID.
  9. 
    package com.journaldev.examples;
    
    import java.util.UUID;
    
    /**
     * Java UUID Least and Most Significant Bits Example Program
     *
     */
    public class UUIDLsbMsbExample {
    
    	public static void main(String[] args) {
    		
    		//initialize uuid
    		UUID uuid = UUID.randomUUID();
    		System.out.println("UUID : "+uuid);
    		System.out.println("Least Significant Bits : "+uuid.getLeastSignificantBits());
    		System.out.println("Most Significant Bits : "+uuid.getMostSignificantBits());
    	}
    
    }
    

    Output of the above java UUID example program is:

    
    UUID : 5b08be16-2cb6-46d5-bf98-7d7d750df0ca
    Least Significant Bits : -4640821438217064246
    Most Significant Bits : 6559701859713828565
    
  10. nameUUIDFromBytes(byte[] name): This is a static factory method and used to fetch name-based (version 3) UUID using specified byte array.
  11. 
    package com.journaldev.examples;
    
    import java.util.UUID;
    
    /**
     * Java UUID From Byte Array Example Program
     *
     */
    public class UUIDFromBytesExample {
    
    	public static void main(String[] args) {
    		
    		//initialize byte array
    		byte[] bs = {1, 2, 3};
    		//initialize uuid using byte array
    		UUID uuid = UUID.nameUUIDFromBytes(bs);
    		System.out.println("UUID : "+uuid);
    		System.out.println("UUID Version : "+uuid.version());
    
    	}
    
    }
    

    Output of the above program is:

    
    UUID : 5289df73-7df5-3326-bcdd-22597afb1fac
    UUID Version : 3
    
  12. node(): This method returns long value of node from UUID and to fetch node value we need to create time-based (version 1) UUID otherwise it will throw UnsupportedOperationException.
  13. 
    package com.journaldev.examples;
    
    import java.util.UUID;
    
    import com.fasterxml.uuid.Generators;
    
    /**
     * Java UUID Node Example Program
     *
     */
    public class UUIDNodeExample {
    
    	public static void main(String[] args) {
    		//Generate time-based uuid
    		UUID uuid = Generators.timeBasedGenerator().generate();
    		System.out.println("UUID : "+uuid);
    		System.out.println("UUID Version : "+uuid.version());
    		System.out.println("UUID Node : "+uuid.node());
    
    	}
    
    }
    
    
    UUID : 2e15baa3-d272-11e7-a479-05de8af2b6bd
    UUID Version : 1
    UUID Node : 6453372040893
    
  14. timestamp(): This method returns timestamp value of UUID UUID and to fetch timestamp value we need to create time-based(version 1) UUID otherwise it will throw UnsupportedOperationException.

package com.journaldev.examples;

import java.util.UUID;

import com.fasterxml.uuid.Generators;

/**
 * Java UUID timestamp Example Program
 *
 */
public class UUIDTimestampExample {

	public static void main(String[] args) {
		// Generate time-based uuid
		UUID uuid = Generators.timeBasedGenerator().generate();
		System.out.println("UUID : " + uuid);
		System.out.println("UUID Version : " + uuid.version());
		System.out.println("UUID Timestamp : " + uuid.timestamp());

	}

}

Output of the above program is:


UUID : 61614667-d279-11e7-a5ac-f941ac8dfc39
UUID Version : 1
UUID Timestamp : 137309732424730215

Create UUID Using Constructor

Let’s have a look at the below example program to create UUID using it’s constructor.


package com.journaldev.examples;

import java.util.UUID;

/**
 * Java UUID Using Constructor Example Program
 *
 */
public class UUIDUsingConstructor {

	public static void main(String[] args) {
		long msb = System.currentTimeMillis();
		long lsb = System.currentTimeMillis();
		//initialize uuid
		UUID uuid = new UUID(msb, lsb);
		System.out.println("UUID : "+uuid);
	}

}

Compare Two UUIDs

Java UUID class provides two methods to compare UUIDs.

  1. compareTo(UUID val): UUID class implements Comparable interface. This method compare UUID with specified value of UUID and returns integer value which can be -1, 0 or 1.
    • -1: This UUID is less than specified value of UUID
    • 0: This UUID is equal to specified value of UUID
    • 1: This UUID is greater than specified value of UUID

    Let’s have a look at the below example program.

    
    package com.journaldev.examples;
    
    import java.util.UUID;
    
    /**
     * Java UUID compareTo Example Program
     *
     */
    public class UUIDCompareToExample {
    
    	public static void main(String[] args) {
    		//initialize uuids
    		UUID uuid1 = UUID.randomUUID();
    		UUID uuid2 = UUID.randomUUID();
    		
    		int result = uuid1.compareTo(uuid2);
    		if (result == -1) {
    			System.out.println("UUID1 is less than UUID2");
    		}else if (result == 0) {
    			System.out.println("Both are Equal UUID");
    		}else if (result == 1) {
    			System.out.println("UUID1 is greater than UUID2");
    		}
    
    	}
    
    }
    

    Output will depend on the randomly generated UUID values, we can’t predict it.

  2. equals(Object obj): This method compares UUID with specified object and returns true if the specified object is not null and is of type UUID and is of same variant and contains the same value.

package com.journaldev.examples;

import java.util.UUID;

/**
 * Java UUID equals Example Program
 *
 */
public class UUIDEqualsExample {

	public static void main(String[] args) {

		// initialize uuids
		UUID uuid1 = UUID.randomUUID();
		UUID uuid2 = UUID.randomUUID();
		
		System.out.println(uuid1.equals(uuid2));

	}

}

That’s all for Java UUID class. It’s a great utility class and you can use it to create unique identifiers.

Reference: API Doc, RFC 4122

Comments

  1. Baz Mathew says:

    How would you convert the following HEX to GUID?
    HEX: 75271f99744c55479e8216f8f5017672
    Guid: 991f2775-4c74-4755-9e82-16f8f5017672

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages