How to generate UUID / GUID in Java?

UUID / GUID in Java can be generated using java.util.UUID class. java.util.UUID class was introduced in java in 1.5 version.

UUID / GUID in Java is generally used as an unique identifier. It can be used as an unique identifier in database.

Demo Program to generate UUID / GUID in Java

package com.masterjavatutorial;

import java.util.UUID;

public class TestExample {
	public static void main(String[] args){
		UUID randomUUID = UUID.randomUUID(); 
		String uuidStr = randomUUID.toString();
		System.out.println("Random UUID = "+uuidStr); 
		System.out.println("UUID Version ="+randomUUID.version()); 
		System.out.println("UUID Variant ="+randomUUID.variant()); 

Output of the above Program is as below:

Random UUID = cb849c8b-f312-4b8e-b6e0-2129f5041b9f
UUID Version =4
UUID Variant =2

version() method is used to get the version of UUID being used and variant() method indicates which variant of UUID is getting used.