Java UUID
UUID Generation
Java Programming
UUID without Dashes
Random UUID

Efficient method to generate UUID String in Java UUID.randomUUID.toString without the dashes

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

The most efficient way to generate a UUID string without dashes in Java is UUID.randomUUID().toString().replace("-", ""). This produces a 32-character hexadecimal string from a cryptographically strong random UUID. For applications where even the overhead of replace() matters, you can format the UUID's getMostSignificantBits() and getLeastSignificantBits() directly into a hex string, avoiding the intermediate dashed string entirely.

java
1import java.util.UUID;
2
3// Simple approach (sufficient for nearly all use cases)
4String id = UUID.randomUUID().toString().replace("-", "");
5// Example: "550e8400e29b41d4a716446655440000"

How UUID.randomUUID() Works

UUID.randomUUID() generates a Version 4 UUID, which uses 122 bits of cryptographically secure random data (the remaining 6 bits encode the version and variant). The underlying random source is SecureRandom, which means the method is suitable for security-sensitive identifiers like session tokens and API keys.

A standard UUID string looks like this:

text
550e8400-e29b-41d4-a716-446655440000
  8       4    4    4       12        = 32 hex chars + 4 dashes = 36 chars

The groups follow the 8-4-4-4-12 pattern defined in RFC 4122. Removing the four dashes gives you a compact 32-character string.

For the vast majority of applications, the replace() approach is the right choice. It is clear, correct, and fast enough.

java
1import java.util.UUID;
2
3public class UuidGenerator {
4    public static String generateCompactUuid() {
5        return UUID.randomUUID().toString().replace("-", "");
6    }
7
8    public static void main(String[] args) {
9        for (int i = 0; i < 5; i++) {
10            System.out.println(generateCompactUuid());
11        }
12    }
13}

Output:

text
a3f4b2c1d5e6789012345678abcdef01
b7c8d9e0f1a2345678901234bcde5678
...

Performance of replace()

String.replace("-", "") scans the 36-character string once and produces a new 32-character string. This takes on the order of nanoseconds. Even generating millions of UUIDs per second, the replace() call is not the bottleneck. SecureRandom (used internally by randomUUID()) is the expensive part.

Method 2: Direct Hex Formatting (Zero-Allocation Path)

If you are generating UUIDs in a hot loop and profiling shows that string allocation matters, you can bypass toString() entirely and format the raw bits yourself.

java
1import java.util.UUID;
2
3public class FastUuidGenerator {
4    private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
5
6    public static String generateCompactUuid() {
7        UUID uuid = UUID.randomUUID();
8        long msb = uuid.getMostSignificantBits();
9        long lsb = uuid.getLeastSignificantBits();
10
11        char[] chars = new char[32];
12        for (int i = 0; i < 16; i++) {
13            long val = (i < 8) ? msb : lsb;
14            int shift = (i < 8) ? (56 - i * 8) : (120 - i * 8);
15            int b = (int) ((val >>> shift) & 0xFF);
16            chars[i * 2] = HEX_CHARS[b >>> 4];
17            chars[i * 2 + 1] = HEX_CHARS[b & 0x0F];
18        }
19
20        return new String(chars);
21    }
22
23    public static void main(String[] args) {
24        System.out.println(generateCompactUuid());
25    }
26}

This avoids creating the intermediate 36-character dashed string. In benchmarks, it is roughly 2x faster than the replace() approach, but the absolute difference is measured in nanoseconds. Use this only if profiling justifies it.

Method 3: Using Long.toHexString()

A simpler manual approach uses Long.toHexString() with zero-padding:

java
1import java.util.UUID;
2
3public class HexUuidGenerator {
4    public static String generateCompactUuid() {
5        UUID uuid = UUID.randomUUID();
6        return String.format("%016x%016x",
7            uuid.getMostSignificantBits(),
8            uuid.getLeastSignificantBits());
9    }
10
11    public static void main(String[] args) {
12        System.out.println(generateCompactUuid());
13    }
14}

The %016x format specifier ensures each half is zero-padded to 16 hex characters. Without zero-padding, leading zeros would be dropped, producing a shorter-than-expected string.

Performance Comparison

MethodAllocationsRelative SpeedCode Complexity
toString().replace("-", "")2 strings (dashed + compact)BaselineMinimal
String.format("%016x%016x", ...)1 string + format overheadSlightly slower (format parsing)Low
Direct char array construction1 string (compact only)About 2x fasterMedium
StringBuilder approach1 StringBuilder + 1 stringSimilar to replaceLow

For context, UUID.randomUUID() itself takes roughly 1-3 microseconds because it calls SecureRandom.nextBytes(). The string formatting takes 50-200 nanoseconds. Optimizing the formatting step only matters if UUID generation is not the bottleneck, which is unusual.

Using Third-Party Libraries

Apache Commons Codec

If your project already depends on Apache Commons, you can use its hex utilities, though there is no dedicated UUID-without-dashes method:

java
1import org.apache.commons.codec.binary.Hex;
2import java.nio.ByteBuffer;
3import java.util.UUID;
4
5UUID uuid = UUID.randomUUID();
6ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
7bb.putLong(uuid.getMostSignificantBits());
8bb.putLong(uuid.getLeastSignificantBits());
9String compact = Hex.encodeHexString(bb.array());

com.fasterxml.uuid (Java UUID Generator)

For high-throughput scenarios, the java-uuid-generator library offers time-based (v1) and name-based (v3/v5) UUIDs with optimized string generation:

xml
1<dependency>
2    <groupId>com.fasterxml.uuid</groupId>
3    <artifactId>java-uuid-generator</artifactId>
4    <version>5.0.0</version>
5</dependency>
java
import com.fasterxml.uuid.Generators;

String id = Generators.randomBasedGenerator().generate().toString().replace("-", "");

For most projects, the standard java.util.UUID is sufficient and adds no dependencies.

UUID Versions: When to Use What

Not all UUIDs are random. Understanding the versions helps you choose the right one:

VersionGeneration MethodUse CaseDashless String Safe?
v1Timestamp + MAC addressTime-ordered IDsYes
v3MD5 hash of namespace + nameDeterministic IDs from inputYes
v4Cryptographic randomGeneral-purpose unique IDsYes
v5SHA-1 hash of namespace + nameDeterministic IDs (preferred over v3)Yes
v7Unix timestamp + randomTime-ordered, sortable, database-friendlyYes

Java's UUID.randomUUID() generates v4. For database primary keys, v7 (time-sorted) UUIDs are increasingly preferred because they produce sequential inserts, which are friendlier to B-tree indexes.

Database Considerations

When storing dashless UUIDs as database keys, choose the column type carefully:

sql
1-- MySQL: BINARY(16) is most space-efficient
2CREATE TABLE users (
3    id BINARY(16) PRIMARY KEY,
4    name VARCHAR(255)
5);
6
7-- PostgreSQL: native UUID type (stores as 128-bit value regardless of input format)
8CREATE TABLE users (
9    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
10    name VARCHAR(255)
11);
12
13-- If storing as text (less efficient but human-readable)
14CREATE TABLE users (
15    id CHAR(32) PRIMARY KEY,
16    name VARCHAR(255)
17);

For MySQL, BINARY(16) uses half the storage of CHAR(32) and indexes more efficiently. Convert between hex string and binary in Java:

java
1import java.nio.ByteBuffer;
2import java.util.UUID;
3
4public static byte[] uuidToBytes(UUID uuid) {
5    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
6    bb.putLong(uuid.getMostSignificantBits());
7    bb.putLong(uuid.getLeastSignificantBits());
8    return bb.array();
9}

Thread Safety

UUID.randomUUID() is thread-safe. The underlying SecureRandom instance handles concurrent access correctly. You do not need synchronization, thread-local instances, or object pools when generating UUIDs from multiple threads.

java
1// Safe to call from any thread, no synchronization needed
2ExecutorService pool = Executors.newFixedThreadPool(8);
3for (int i = 0; i < 1000; i++) {
4    pool.submit(() -> {
5        String id = UUID.randomUUID().toString().replace("-", "");
6        // use id
7    });
8}

Common Pitfalls

Forgetting zero-padding with Long.toHexString(). Long.toHexString() does not pad to 16 characters. If the most significant bits start with zeros, the output will be shorter than 32 characters. Use String.format("%016x", ...) instead.

Using Math.random() or ThreadLocalRandom to build "UUIDs." These are not cryptographically secure and do not follow the UUID specification. The resulting strings have a higher collision probability and should not be used as unique identifiers in distributed systems.

Storing dashless UUIDs as VARCHAR instead of BINARY. A CHAR(32) column uses 32 bytes. A BINARY(16) column uses 16 bytes. For tables with millions of rows, the index size difference is substantial.

Assuming all UUIDs are random. If you receive UUIDs from external systems, they may be v1 (timestamp-based) and contain information about the machine that generated them. Do not treat UUID version as a security assumption.

Re-parsing UUIDs with UUID.fromString() on dashless strings. UUID.fromString() requires the standard 8-4-4-4-12 dashed format. To parse a dashless string, reinsert the dashes first or use a library.

java
1// Parsing a dashless UUID back into a UUID object
2String compact = "550e8400e29b41d4a716446655440000";
3String dashed = compact.replaceFirst(
4    "(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})",
5    "$1-$2-$3-$4-$5"
6);
7UUID uuid = UUID.fromString(dashed);

Summary

  • Use UUID.randomUUID().toString().replace("-", "") for a 32-character hex string without dashes. This is correct, readable, and fast enough for nearly all applications.
  • For hot-loop performance, format the UUID's raw long values directly into a char[] array to skip the intermediate dashed string.
  • UUID.randomUUID() is thread-safe and uses SecureRandom, making it suitable for security-sensitive identifiers.
  • Store UUIDs as BINARY(16) in databases for space efficiency, not as CHAR(32) or VARCHAR(36).
  • Always zero-pad when using manual hex conversion. Leading zeros matter for UUID correctness.
  • Consider v7 UUIDs for database primary keys when sort order matters, as they produce sequential values friendly to B-tree indexes.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.