Java UUID
UUID Generation
Java Programming
UUID without Dashes
Random UUID

Java UUID without dashes: UUID.randomUUID().toString().replace("-", "")

Codemia Knowledge Hub ·

The simplest efficient way to get a UUID string without dashes in Java is UUID.randomUUID().toString().replace("-", ""), which gives a 32-character hexadecimal string from a cryptographically strong random UUID. If even the replace() overhead matters, format the UUID's getMostSignificantBits() and getLeastSignificantBits() straight into a hex string and skip the intermediate dashed string.

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

What UUID.randomUUID() generates

UUID.randomUUID() creates a Version 4 UUID: 122 bits of cryptographically secure random data, with the remaining 6 bits encoding the version and variant. The random source is SecureRandom, so the method is suitable for security-sensitive identifiers such as 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 8-4-4-4-12 grouping is defined in RFC 4122. Removing the four dashes leaves a compact 32-character string.

For almost every application, replace() 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
a3f4b2c1d5e64890a234567890abcdef
b7c8d9e0f1a245689890bcde12345678
...

String.replace("-", "") scans the 36-character string once and builds a new 32-character string, which takes nanoseconds. Even at millions of UUIDs per second, it is not the bottleneck; SecureRandom inside randomUUID() is the expensive part.

Direct hex formatting into a char array

If you generate UUIDs in a hot loop and profiling shows that string allocation matters, bypass toString() 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 the intermediate 36-character dashed string. In benchmarks it is roughly 2x faster than replace(), but the absolute difference is in nanoseconds, so use it only if profiling justifies it.

String.format with %016x

A simpler manual approach formats both halves 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}

%016x pads each half to 16 hex characters. Long.toHexString() does not pad, so if the most significant bits start with zeros its output is shorter than 32 characters. Always zero-pad when converting by hand.

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

UUID.randomUUID() itself takes roughly 1-3 microseconds because it calls SecureRandom.nextBytes(), while the string formatting takes 50-200 nanoseconds. Optimizing the formatting only matters in the unusual case where UUID generation is not the bottleneck.

Third-party libraries

Apache Commons Codec

If you already depend on Apache Commons, its hex utilities work, 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());

Java UUID Generator (com.fasterxml.uuid)

For high-throughput scenarios, java-uuid-generator 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 enough and adds no dependencies.

UUID versions

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, time-sorted v7 UUIDs are increasingly preferred because sequential inserts are friendlier to B-tree indexes. Also, UUIDs from external systems may be v1 and reveal information about the machine that generated them, so don't treat the UUID version as a security assumption.

Storing dashless UUIDs in a database

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);

In MySQL, BINARY(16) uses 16 bytes against 32 for CHAR(32), and indexes more efficiently; on tables with millions of rows the index size difference is substantial. Convert a UUID to bytes in Java with:

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, because the underlying SecureRandom handles concurrent access. You don't need synchronization, thread-local instances or object pools:

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}

Pitfalls

Building "UUIDs" from Math.random() or ThreadLocalRandom. These are not cryptographically secure and don't follow the UUID specification. The strings have a higher collision probability and should not be used as unique identifiers in distributed systems.

Parsing dashless strings with UUID.fromString(). It requires the standard 8-4-4-4-12 dashed format, so 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);

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
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms