UUID Random Parse Roundtrip

Generate random UUIDv4 identifiers with randomUUID, parse canonical text back with fromString, and rely on fromString rejecting malformed input.

JavaData Integrity

Code

snippet
import java.util.UUID;

public class IdempotencyKey {

    public static void main(String[] args) {
        // 随机 UUID(randomUUID):version 4,带固定版本/变体位
        UUID key = UUID.randomUUID();
        System.out.println("version: " + key.version() + " variant: " + key.variant());

        // canonical 文本固定 36 字符(8-4-4-4-12)
        String text = key.toString();
        System.out.println("length: " + text.length());

        // fromString 解析回对象:equals 与 toString 往返一致
        UUID parsed = UUID.fromString(text);
        System.out.println("roundtrip equals: " + parsed.equals(key));

        // 非法串抛 IllegalArgumentException,而不是静默返回 null
        try {
            UUID.fromString("not-a-uuid");
        } catch (IllegalArgumentException e) {
            System.out.println("invalid input rejected");
        }
    }
}

How the snippet works

The snippet is organized around the class IdempotencyKey and the function main.

Applying it

Running the file prints labeled results such as version:, length:, roundtrip equals: — each operation’s effect is visible in the output.

Statements that matter

UUID parsed = UUID.fromString(text);
UUID.fromString("not-a-uuid");
UUID key = UUID.randomUUID();

Interactive Tools for This Topic

FAQ

What does UUID Random Parse Roundtrip print when run?
The script runs standalone; its 4 labeled outputs include `version:`, `length:`, `roundtrip equals:`.