Over a million developers have joined DZone.

Global unique identifiers in Java, the easy way

DZone's Guide to

Global unique identifiers in Java, the easy way

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

A recent attempt at creating a unique identifier at work was shot down in flames by Findbugs. My naïve attempt wasn’t very thoughtful but seemed to work.


Findbugs indicated there was a possibility that I might end up with a negative value even though I “cleverly” used Math.abs().

RV: Bad attempt to compute absolute value of signed random integer (RV_ABSOLUTE_VALUE_OF_RANDOM_INT)

If the number returned by the random number generator is Integer.MIN_VALUE, then the result will be negative as well

Even though I didn’t need this random id to be perfect — the unintended side-effect wasn’t a technical problem since I used it as a String — I still wanted to fix it. Stackoverflow to the rescue.

A question-and-answer from Stackoverflow pointed the way to the solution: java.util.UUID. Somehow, I missed that Sun had added Java’s own universally unique identifier (UUID) generator in Java 1.5.

In the end, I happily replaced my homemade id generator with Java’s.


The output of which is something like 1c312843-8903-411f-88b2-ff1b92ca80ba.


From http://codeaweso.me/2011/11/global-unique-identifiers-in-java-the-easy-way/

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}