The java.util.UUID class helps to generate unique identifiers. There are four different types of UUID:

  1. Time-Based
  2. DCE Security
  3. Name-Based
  4. Randomly Generated

The types mentioned above are also known as version values 1, 2, 3 and 4 respectively.

A sample program to generate UUID using Java is as follows:

package com.learning.utils;

import java.util.UUID;

public class UUIDGenerator {

	public static void main(String[] args) {

		//Generate Random UUID
		UUID randomUUID = UUID.randomUUID();
		System.out.println("randomUUID = " + randomUUID);
		System.out.println("==========================================================================");
		
		
		//UUID From Given String. String should follow the given format else IllegalArgumentException will be thrown. The required format contains "-" minus four signs between alphanumeric values. 
		String strForUUID = "4bcac14b-48bd-4026-b5e8-58a6708f93df";
		UUID uuidGeneratedFromGivenString = UUID.fromString(strForUUID);
		System.out.println("uuidGeneratedFromGivenString = " + uuidGeneratedFromGivenString);
		System.out.println("==========================================================================");
		
		

		//UUID From Given Bytes. While using Bytes the above mentioned format which contains minus "-" sign in between, is not necessary
		String strForUUIDBytes = "TestString";
		UUID uuidGeneratedStrBytes = UUID.nameUUIDFromBytes(strForUUIDBytes.getBytes());
		System.out.println("uuidGeneratedStrBytes =" + uuidGeneratedStrBytes);
		
		
	}
}

The output generated by code is as follows.

randomUUID = 19405a18-a6cb-4e05-8fcb-7f1400f3ddcb
==========================================================================
uuidGeneratedFromGivenString = 4bcac14b-48bd-4026-b5e8-58a6708f93df
==========================================================================
uuidGeneratedStrBytes =5b56f40f-8828-301f-97fa-4511ddcd25fb