How to generate UUID / GUID in Java

  • 19 June 2018
  • ADM


How to generate UUID / GUID in Java - images/logos/java.jpg


To generate a UUID / GUID (Universally / Globally Unique Identifier) in Java you can use java.util.UUID class, the method UUID.randomUUID() that will return a UUID Object. The class was introduced in Java 1.5.


package com.admfactory.basic;

import java.util.UUID;

public class GUIDExample {
    public static void main(String[] args) {
	System.out.println("Creating random UUID/GUID in Java");

	UUID uuid = UUID.randomUUID();
	String uuidStr = uuid.toString();
	System.out.println("Random UUID[1]: " + uuidStr);

	uuid = UUID.randomUUID();
	uuidStr = uuid.toString();
	System.out.println("Random UUID[2]: " + uuidStr);


Creating random UUID/GUID in Java

Random UUID[1]: f2d8afc1-6dd8-4dc6-ad26-dc701284e43c
Random UUID[2]: cfb962cb-470c-4409-98aa-9f61c4efd92b