Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

UUID.randomUUID()

Creates a random UUID — a 128-bit identifier that practically never repeats.

Available since: Java 5

Syntax

public static UUID randomUUID()

Return value

UUIDA new version 4 UUID.

Examples

A new identifier on every call:

void main() {
    UUID id = UUID.randomUUID();
 
    IO.println(id);
    IO.println(id.toString().length());
    IO.println(id.version());
}

Output:

aedfd805-b0d7-42ce-9121-5d0dda73d486
36
4

UUID.fromString() parses a string; letter case does not matter:

void main() {
    UUID a = UUID.fromString("3f2a6c1e-8b4d-4c7a-9e21-5d0f7b3a9c44");
    UUID b = UUID.fromString("3F2A6C1E-8B4D-4C7A-9E21-5D0F7B3A9C44");
 
    IO.println(a.equals(b));
    IO.println(b);
}

Output:

true
3f2a6c1e-8b4d-4c7a-9e21-5d0f7b3a9c44

Notes

The string form is 36 characters: 32 hexadecimal digits and 4 hyphens. Version 4 contains 122 random bits from SecureRandom, so a collision is practically impossible. A UUID is handy as a record key that can be created without a database. UUID.nameUUIDFromBytes(bytes) always gives the same (version 3) UUID for the same bytes. An invalid string in fromString() throws IllegalArgumentException.

See also

  • Random — A random number generator: integers in a range, decimals, booleans.
  • String.toUpperCase() — Returns a copy of the string with all letters in upper case.
  • Object.equals() — Compares objects by meaning. By default it works like ==, so classes override it.

In the tutorial

  • Classes and objects — What classes and objects are in Java: fields, methods, the new operator, default values and object references.

Thanks for reading!

Donate to the site — we work hard for you.