Generating a UUID in Java

Published on October 13, 2015 by

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.

Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

2 comments on »Generating a UUID in Java«

  1. SDN

    where I can find the GeneralUtils class ?

    This details out the version 4 UUIDs

    • Hello,

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

Leave a Reply

Your e-mail address will not be published.