The Wayback Machine - http://web.archive.org/web/20241127011012/https://www.geeksforgeeks.org/java-util-uuid-class-java/
Open In App

Java.util.UUID class in Java

Last Updated : 19 Jan, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A class that represents an immutable universally unique identifier (UUID). A UUID represents a 128-bit value. There exist different variants of these global identifiers. The methods of this class are for manipulating the Leach-Salz variant, although the constructors allow the creation of any variant of UUID (described below). 
There are four different basic types of UUIDs: time-based, DCE security, name-based, and randomly generated UUIDs. These types have a version value of 1, 2, 3 and 4, respectively. 

  • Used to create session id in web application. It is also used to create transaction id.
  • It extends Object class.
  • It implements Serializable and Comparable interfaces.

Constructor:  

UUID(long mostSigBits, long leastSigBits)

Constructs a new UUID using the specified data. 
mostSigBits – The most significant bits of the UUID 
leastSigBits – The least significant bits of the UUID 

Methods: 

  • int clockSequence(): The clock sequence value associated with this UUID. 
    The 14 bit clock sequence value is constructed from the clock sequence field of this UUID. The clock sequence field is used to guarantee temporal uniqueness in a time-based UUID. 
    The clockSequence value is only meaningful in a time-based UUID, which has version type 1. If this UUID is not a time-based UUID then this method throws UnsupportedOperationException.
Syntax: public int clockSequence().
Returns: The clock sequence of this UUID.
Exception: 
UnsupportedOperationException - If this UUID is not a version 1 UUID

Java




// Java code illustrating clockSequence() method
import java.util.UUID;
class UUIDdemo
{
    public static void main(String arg[]) throws
            UnsupportedOperationException
    {
        UUID gfg = UUID.fromString("c81d4e2e-bcf2-11e6-869b-7df92533d2db");
         
        // checking clock sequence
        System.out.println(gfg.clockSequence());
    }
}


Output: 

1691
  • int compareTo(UUID val): Compares this UUID with the specified UUID. 
    The first of two UUIDs is greater than the second if the most significant field in which the UUIDs differ is greater for the first UUID.
Syntax: public int compareTo(UUID val).
Returns: -1, 0 or 1 as this UUID is less than, equal to, or greater than val.
Exception: NA.

Java




// Java code illustrating compareTo() method
import java.util.UUID;
class UUIDdemo
{
    public static void main(String arg[])
    {
        // generating random UUID
        UUID gfg1 = UUID.randomUUID();
        UUID gfg2 = UUID.randomUUID();
         
        int compare = gfg1.compareTo(gfg2);
        if(compare==1)
            System.out.println("gfg1 is greater than gfg2");
        else if(compare==0)
            System.out.println("both are equal");
        else
            System.out.println("gfg1 is smaller than gfg2");  
    }
}


Output: 

gfg1 is smaller than gfg2
  • boolean equals(Object obj): Compares this object to the specified object. The result is true if and only if the argument is not null, is a UUID object, has the same variant, and contains the same value, bit for bit, as this UUID.
Syntax: public boolean equals(Object obj).
Returns: true if the objects are the same; false otherwise
Exception: NA.

Java




// Java code illustrating equals() method
import java.util.UUID;
class UUIDdemo
{
    public static void main(String arg[])
    {
        // generating random UUID
        UUID gfg1 = UUID.randomUUID();
        UUID gfg2 = UUID.randomUUID();
         
        if(gfg1.equals(gfg2))
            System.out.println("both are equal");
        else
            System.out.println("both are not same");
    }
}


Output: 

both are not same
  • static UUID fromString(String name): Creates a UUID from the string standard representation as described in the toString() method.
Syntax: public static UUID fromString(String name).
Returns: a UUID with the specified value.
Exception: 
IllegalArgumentException - If name does not conform to the string 
representation as described in toString()

Java




// Java code illustrating fromString() method
import java.util.UUID;
class UUIDdemo
{
    public static void main(String arg[])
    {
        // generating random UUID
        UUID gfg = UUID.fromString("e52232e1-0ded-4587-999f-4dd135a4a94f");
        System.out.println("UUID is: " + gfg);
    }
}


Output: 

UUID is: e52232e1-0ded-4587-999f-4dd135a4a94f
  • long getLeastSignificantBits(): This method returns the least significant 64 bits of this UUID’s 128 bit value.
Syntax: public long getLeastSignificantBits().
Returns: The least significant 64 bits of this UUID's 128 bit value.
Exception: NA.

Java




// Java code illustrating getLeastSignificantBits() method
import java.util.UUID;
class UUIDdemo
{
    public static void main(String arg[])
    {
        UUID gfg = UUID.randomUUID();
         
        // checking the least significant bit
        System.out.println("Least significant bit " +
                gfg.getLeastSignificantBits());
    }
}


Output: 

Least significant bit -8406445530268383532
  • long getMostSignificantBits(): This method returns the most significant 64 bits of this UUID’s 128 bit value.
Syntax: public long getMostSignificantBits()
Returns: The most significant 64 bits of this UUID's 128 bit value.
Exception: NA

Java




// Java code illustrating getMostSignificantBits() bit
import java.util.UUID;
class UUIDdemo
{
    public static void main(String arg[])
    {
        UUID gfg = UUID.randomUUID();
         
        // checking the most significant bit
        System.out.println("Most significant bit " +
                gfg.getMostSignificantBits());
    }
}


Output: 

Most significant bit 8138958362250724568
  • int hashCode(): this method returns hash code for this UUID.
Syntax: public int hashCode().
Returns: the hash code for this UUID.
Exception: NA.

Java




// Java code illustrating hashCode method
import java.util.UUID;
class UUIDdemo
{
    public static void main(String arg[])
    {
        UUID gfg = UUID.randomUUID();
         
        // checking the hash code for this UUID
        System.out.println("Hash code " +
                gfg.hashCode());
    }
}


Output: 

Hash code -2073067668
  • static UUID nameUUIDFromBytes(byte[] name): Static factory to retrieve a type 3 (name based) UUID based on the specified byte array.
Syntax: public static UUID nameUUIDFromBytes(byte[] name)
Returns: A UUID generated from the specified array.
Exception: NA.

Java




// Java code illustrating nameUUIDFromBytes() methods
import java.util.UUID;
class UUIDdemo
{
    public static void main(String arg[]) throws
         UnsupportedOperationException
    {
        // creating byte array
        byte[] b = {10, 23, 45};
         
        // creating UUID from array
        UUID gfg = UUID.nameUUIDFromBytes(b);
         
        // checking UUID
        System.out.println(gfg);
    }
}


Output: 

f76a74ae-83b6-389c-82ca-8ac0b9febd33
  • long node(): The node value associated with this UUID. 
    The 48 bit node value is constructed from the node field of this UUID. This field is intended to hold the IEEE 802 address of the machine that generated this UUID to guarantee spatial uniqueness. 
    The node value is only meaningful in a time-based UUID, which has version type 1. If this UUID is not a time-based UUID then this method throws UnsupportedOperationException.
Syntax: public long node().
Returns: The node value of this UUID.
Exception: 
UnsupportedOperationException - If this UUID is not a version 1 UUID

Java




// Java code illustrating node() method
import java.util.UUID;
class UUIDdemo
{
    public static void main(String arg[]) 
    {
        UUID gfg = UUID.fromString("c81d4e2e-bcf2-11e6-869b-7df92533d2db");
         
        // checking node value for this UUID
        System.out.println("Node value: "
          + gfg.node());
    }
}


Output: 

Node value: 138509024482011
  • static UUID randomUUID(): Static factory to retrieve a type 4 (pseudo randomly generated) UUID. The UUID is generated using a cryptographically strong pseudo random number generator.
Syntax: public static UUID randomUUID().
Returns: randomly generated UUID.
Exception: NA

Java




// Java code illustrating randomUUID() method
import java.util.UUID;
class UUIDdemo
{
    public static void main(String arg[]) throws
            UnsupportedOperationException
    {
        UUID gfg = UUID.randomUUID();
         
        // checking  this UUID
        System.out.println("UUID: "
          + gfg);
    }
}


Output: 

UUID: 937418f1-f1b6-4f7a-b9f6-9fa51ba780e3
  • long timestamp(): The timestamp value associated with this UUID. 
    The 60 bit timestamp value is constructed from the time_low, time_mid, and time_hi fields of this UUID. The resulting timestamp is measured in 100-nanosecond units since midnight, October 15, 1582 UTC. 
    The timestamp value is only meaningful in a time-based UUID, which has version type 1. If this UUID is not a time-based UUID then this method throws UnsupportedOperationException.
Syntax: public long timeStamp().
Returns: the time stamp value.
Exception: NA.

Java




// Java code illustrating timeStamp() method
import java.util.UUID;
class UUIDdemo
{
    public static void main(String arg[]) throws
            UnsupportedOperationException
    {
        UUID gfg = UUID.fromString("c81d4e2e-bcf2-11e6-869b-7df92533d2db");
         
        // checking time stamp for this UUID
        System.out.println("time stamp: "
          + gfg.timestamp());
    }
}


Output: 

time stamp: 137004589606850094
  • String toString(): This method returns a String object representing this UUID.
Syntax: public String toString().
Returns: a string object for this UUID.
Exception: NA

Java




// Java code illustrating toString method
import java.util.UUID;
class UUIDdemo
{
    public static void main(String arg[]) throws
            UnsupportedOperationException
    {
        UUID gfg = UUID.fromString("c81d4e2e-bcf2-11e6-869b-7df92533d2db");
         
        // checking string format for this UUID
        System.out.println("String equivalent: "
          + gfg.toString());
    }
}


Output: 

String equivalent: c81d4e2e-bcf2-11e6-869b-7df92533d2db
  • int variant(): The variant number associated with this UUID. The variant number describes the layout of the UUID.
Syntax: public int variant()
Returns: The variant number of this UUID
Exception: NA

Java




// Java code illustrating variant() method
import java.util.UUID;
class UUIDdemo
{
    public static void main(String arg[]) throws
            UnsupportedOperationException
    {
        UUID gfg = UUID.fromString("c81d4e2e-bcf2-11e6-869b-7df92533d2db");
         
        // checking variant number for this UUID
        System.out.println("variant number is: "
          + gfg.variant());
    }
}


Output: 

variant number is: 2
  • int version(): The version number associated with this UUID. The version number describes how this UUID was generated. The version number has the following meaning: 
    • 1 Time-based UUID
    • 2 DCE security UUID
    • 3 Name-based UUID
    • 4 Randomly generated UUID


Previous Article
Next Article

Similar Reads

UUID timestamp() Method in Java with Examples
The timestamp() method of UUID class in Java is generally used to get the stamp value associated with a particular UUID. Syntax: public long timestamp() Parameters: This method does not take any parameter. Return Value: This method returns the time stamp value of this UUID. Exception: This method throws UnsupportedOperationException if this UUID is
1 min read
UUID hashCode() Method in Java with Examples
The hashCode() method of UUID class in Java is generally used to get the hash code value of the UUID. Syntax: public int hashCode() Parameters: This method does not take any parameter. Return Value: This method returns an integer value which is the hashCode value for this UUID instance. Below programs illustrate the working of hashCode() method: Pr
1 min read
UUID node() Method in Java with Examples
The node() method of UUID class in Java is generally used to get the node value associated with this UUID. Syntax: public long node() Parameters: This method does not take any parameter. Return Value: This method returns an long value which is the node value associated with this UUID. Exception: This method throws UnsupportedOperationException If t
1 min read
UUID toString() Method in Java with Examples
The toString() method of UUID class in Java is generally used to get the string representation of this UUID. Syntax: public String toString() Parameters: This method does not take any parameter. Return Value: This method returns a String value which is the string representation of this UUID. Below programs illustrate the working of toString() metho
1 min read
UUID nameUUIDFromBytes() Method in Java with Examples
The nameUUIDFromBytes() method of UUID class in Java is generally used to retrieve a third type name based UUID based on the specified byte array. This is used as a static factory method. Syntax: public static UUID nameUUIDFromBytes(byte[] byte_name) Parameters: This method accepts a parameter byte_name which refers to the byte array that is used t
2 min read
UUID version() Method in Java with Examples
Every UUID has a version number describing the generation of this UUID. The version() method of UUID class in Java is generally used to get version number associated with this UUID. Syntax: public int version() Parameters: This method does not take any parameter. Return Value: This method returns a int value which is the version number associated w
1 min read
UUID variant() Method in Java with Examples
Every UUID has a variant number describing the generation of this UUID. The variant() method of UUID class in Java is generally used to get variant number associated with this UUID. Syntax: public int variant() Parameters: This method does not take any parameter. Return Value: This method returns a int value which is the variant number associated w
1 min read
UUID getLeastSignificantBits() Method in Java with Examples
The UUIDs are 128-bit values. The getLeastSignificantBits() Method of UUID class in Java is used to get the least significant 64 bits of this UUID. Syntax: public long getLeastSignificantBits() Parameters: The method does not take any parameters. Return Value: The method returns an integer value which is the least significant 64 bit of this 128 val
2 min read
UUID compareTo() Method in Java with Examples
The compareTo() method of UUID class in Java is used to compare one UUID value with another specified UUID. It returns -1 if this UUID is less than the value, 0 if this UUID is equal to the value, and 1 if this UUID is greater than the value. Syntax: UUID_1.compareTo(UUID_2) Parameters: The method takes one parameter UUID_2 to which the UUID_1 is t
2 min read
UUID fromString() Method in Java with Examples
The fromString() method of UUID class in Java is used for the creation of UUID from the standard string representation of the same. Syntax: public static UUID fromString(String UUID_name) Parameters: The method takes one parameter UUID_name which is the string representation of the UUID. Return Value: The method returns the actual UUID created from
2 min read
UUID equals() Method in Java with Examples
The equals() method of UUID class in Java is used to check for the equality of one UUID with another. The method returns True if both the UUID's are exactly identical bit by bit. Syntax: public boolean equals(Object uuidObj) Parameters: The method takes one parameter uuidObj to which the UUID_1 is to be compared. Return Value: The method returns tr
2 min read
UUID getMostSignificantBits() Method in Java with Examples
The UUIDs are 128-bit values. The getMostSignificantBits() Method of UUID class in Java is used to get the most significant 64 bits of this UUID. Syntax: public long getMostSignificantBits() Parameters: The method does not take any parameters. Return Value: The method returns an integer value which is the most significant 64 bit of this 128 valued
2 min read
UUID clockSequence() Method in Java with Examples
The clockSequence() method of UUID class in Java is generally used to know the clock sequence value associated with this UUID. The clock sequence field of this UUID is used to create the 14-bit clock sequence value. Syntax: public int clockSequence() Parameters: This method does not take any parameter. Return Value: This method returns a int value
2 min read
UUID Primary Keys in Spring Boot
UUIDs (Universally Unique Identifiers) are commonly used as primary keys in databases. Because they provide a unique identifier across different systems without relying on a centralized authority. In a Spring Boot application, you can use UUIDs as primary keys for your entities. Why use UUID as the primary key in our application: UUIDs are like uni
6 min read
Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?Solution
5 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read
Java.util.concurrent.Phaser class in Java with Examples
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts
7 min read
Java.util.concurrent.RecursiveTask class in Java with Examples
RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method of RecursiveTask. RecursiveTask class is mostly use
2 min read
Java.util.BitSet class in Java with Examples | Set 1
BitSet is a class defined in the java.util package. It creates an array of bits represented by boolean values. Constructors: BitSet class Constructors / \ BitSet() BitSet(int no_Of_Bits)BitSet() : A no-argument constructor to create an empty BitSet object. BitSet(int no_Of_Bits): A one-constructor with an integer argument to create an instance of t
2 min read
Java.util.BitSet class methods in Java with Examples | Set 2
Methods discussed in this post: BitSet class methods. / / | | \ \ set() xor() clone() clear() length() cardinality() We strongly recommend to refer below set 1 as a prerequisite of this. BitSet class in Java | Set 1 set() : java.util.BitSet.set() method is a sets the bit at the specified index to the specified value. Syntax:public void set(int bitp
4 min read
Java.util.zip.DeflaterInputStream class in Java
Implements an input stream filter for compressing data in the "deflate" compression format. Constructor and Description DeflaterInputStream(InputStream in) : Creates a new input stream with a default compressor and buffer size. DeflaterInputStream(InputStream in, Deflater defl) : Creates a new input stream with the specified compressor and a defaul
3 min read
Java.util.zip.InflaterOutputStream class in Java
This class implements an output stream filter for uncompressing data stored in the "deflate" compression format. Constructors InflaterOutputStream(OutputStream out) : Creates a new output stream with a default decompressor and buffer size. InflaterOutputStream(OutputStream out, Inflater infl) : Creates a new output stream with the specified decompr
3 min read
Java.util.zip.InflaterInputStream class in Java
This class implements a stream filter for uncompressing data in the "deflate" compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream. Constructors InflaterInputStream(InputStream in) : Creates a new input stream with a default decompressor and buffer size. InflaterInputStream(InputStream in, Inflat
3 min read
Java.util.zip.ZipOutputStream class in Java
This class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructor : ZipOutputStream(OutputStream out) : Creates a new ZIP output stream. ZipOutputStream(OutputStream out, Charset charset) : Creates a new ZIP output stream. Methods: void close() : Closes
3 min read
Java.util.jar.JarEntry class in Java
This class is used to represent a JAR file entry. Constructors : JarEntry(JarEntry je) : Creates a new JarEntry with fields taken from the specified JarEntry object. JarEntry(String name) : Creates a new JarEntry for the specified JAR file entry name. JarEntry(ZipEntry ze) : Creates a new JarEntry with fields taken from the specified ZipEntry objec
2 min read
Java.util.zip.GZIPInputStream class in Java
This class implements a stream filter for reading compressed data in the GZIP file format. Constructors GZIPInputStream(InputStream in) : Creates a new input stream with a default buffer size. GZIPInputStream(InputStream in, int size) : Creates a new input stream with the specified buffer size. Methods : void close() : Closes this input stream and
2 min read
Java.util.zip.ZipEntry class in Java
This class is used to represent a ZIP file entry. Constructors ZipEntry(String name) : Creates a new zip entry with the specified name. ZipEntry(ZipEntry e) : Creates a new zip entry with fields taken from the specified zip entry. Methods: Object clone() : Returns a copy of this entry. Syntax :public Object clone() Overrides: clone in class Object
4 min read
Java.util.jar.JarInputStream class in Java
The JarInputStream class is used to read the contents of a JAR file from any input stream. It extends the class java.util.zip.ZipInputStream with support for reading an optional Manifest entry. The Manifest can be used to store meta-information about the JAR file and its entries. Constructors JarInputStream(InputStream in) : Creates a new JarInputS
3 min read
Java.util.zip.ZipInputStream class in Java
This class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructors: ZipInputStream(InputStream in) : Creates a new ZIP input stream. ZipInputStream(InputStream in, Charset charset) : Creates a new ZIP input stream Methods : int available() : Returns 0 af
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg