Generating a UUID in Java

Generating a UUID in Java is extremely easy. In fact, it can be done with a single line of code! To generate a type 4 UUID in Java, simply run the following line of code.

String uuid = UUID.randomUUID().toString();

// Example: e03913fb-5951-4964-a88b-47371641fd17

Because you will likely generate UUIDs in many different contexts, here is a handy helper utility for you.

public final class GeneralUtils {
    private GeneralUtils() { }

    public static String generateUUID() {
        return UUID.randomUUID().toString();

It can then be used as follows.

String uuid = GeneralUtils.generateUUID();

Not a huge difference, but I personally find the last line easier to remember. Plus, as long as I remember where my UUID method resides, intelli sense will guide me the rest of the way.

I hope this helps.


  1. SDN said:

    where I can find the GeneralUtils class ?

    This details out the version 4 UUIDs

    November 20, 2016
    • Bo Andersen said:


      You can simply copy the code from this post and add the class to your particular project.

      December 3, 2016

Leave a Reply

Your email address will not be published. Required fields are marked *