Search code examples
javanulluuid

Instance of an empty ("nil") UUID in Java


In Java, how does one generate an instance of an empty/"nil" java.util.UUID object where all 128 bits are zero?

00000000-0000-0000-0000-000000000000

Nil UUIDs are described in:


Solution

  • Constructor

    Use the constructor taking a pair of long integers, both zero.

    java.util.UUID uuid = new UUID( 0 , 0 );  // Or ( 0L , 0L )
    

    Hex String

    You can create a nil UUID from a hex string of zeros in the canonical format.

    java.util.UUID uuid = UUID.fromString( "00000000-0000-0000-0000-000000000000" );
    

    Enum

    You could make this handy within your Java app by defining an enum of this and any other special values that have specific meaning within your business logic.

    package com.example;
    
    import java.util.UUID;
    
    /**
     * @author Basil Bourque. Free forever to use at your own risk.
     */
    public enum UuidSpecific  {
    
        NIL( "00000000-0000-0000-0000-000000000000" ),
        TOLERABLE_UNIQUE_CONSTRAINT_VIOLATION( "e8e6528b-e43c-468b-b661-e24f1b64bee6" );
    
        // Members
        private UUID uuid;
    
        // Constructor
        UuidSpecific ( String uuidHexArg ) {
            this.uuid = java.util.UUID.fromString( uuidHexArg );
        }
    
        // Getters
        UUID getUuid ( ) {
            return this.uuid;
        }
    
    }
    

    Example usage:

    System.out.println("UuidSpecific.NIL : " + UuidSpecific.NIL.getUuid() );