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.
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.
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:
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.
Method 1: String.replace() (Recommended)
For the vast majority of applications, the replace() approach is the right choice. It is clear, correct, and fast enough.
Output:
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.
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:
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
| Method | Allocations | Relative Speed | Code Complexity |
toString().replace("-", "") | 2 strings (dashed + compact) | Baseline | Minimal |
String.format("%016x%016x", ...) | 1 string + format overhead | Slightly slower (format parsing) | Low |
| Direct char array construction | 1 string (compact only) | About 2x faster | Medium |
| StringBuilder approach | 1 StringBuilder + 1 string | Similar to replace | Low |
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:
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:
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:
| Version | Generation Method | Use Case | Dashless String Safe? |
| v1 | Timestamp + MAC address | Time-ordered IDs | Yes |
| v3 | MD5 hash of namespace + name | Deterministic IDs from input | Yes |
| v4 | Cryptographic random | General-purpose unique IDs | Yes |
| v5 | SHA-1 hash of namespace + name | Deterministic IDs (preferred over v3) | Yes |
| v7 | Unix timestamp + random | Time-ordered, sortable, database-friendly | Yes |
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:
For MySQL, BINARY(16) uses half the storage of CHAR(32) and indexes more efficiently. Convert between hex string and binary in Java:
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.
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.
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
longvalues directly into achar[]array to skip the intermediate dashed string. UUID.randomUUID()is thread-safe and usesSecureRandom, making it suitable for security-sensitive identifiers.- Store UUIDs as
BINARY(16)in databases for space efficiency, not asCHAR(32)orVARCHAR(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
- Efficient swapping of elements of an array in Java
- Ehcache - using a ListInteger as the cache value
- EHCache RMI Replication on JBoss/EC2 throws java.rmi.NoSuchObjectException no such object in table
- EJB 3.1 asynchronous method and thread pool
- EJB's - when to use Remote and/or local interfaces?
- ElasticBeanstalk Java, spring active profile
- ElasticSearch Java API asynchronous writing
- Embedded AMQP Java Broker

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack 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.