Generating Random Strings in Java: From Chaos to Performance

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to generate a random string in Java without losing your mind?

\n\n

Imagine: you're writing a registration form for a website. You need to create a unique token for email confirmation. Or generate a password for a new user. Or just make a readable ID for a link. The first thing that comes to mind is to take UUID.randomUUID(), remove the hyphens, and be happy.

\n\n

Stop. Did you know that a seemingly simple action can turn into a bottleneck for performance? The Stack Overflow question "How to generate a random alpha-numeric string" gathered thousands of views for a reason. The devil, as always, is in the details: the choice of random number generator, the algorithm, memory management. In this article, we won't just write code — we'll optimize it to the maximum.

\n\n

Get your IntelliJ IDEA ready. Let's go!

\n\n

1. The simplest (but slowest) way: UUID

\n\n

Let's start with the classic. UUID generates a 128-bit value. If you remove the hyphens, you get 32 characters in hex format (0-9, a-f). This is already an alphanumeric string, but with a limited alphabet.

\n\n
public static String generateWithUUID() {\n    return UUID.randomUUID().toString().replace("-", "");\n}\n
\n\n

Pros: One line of code. No thinking required.

\n

Cons: Cannot control the length. Only hex characters (16 alphabet characters). For passwords — too weak. For tokens — it'll do, but there's a catch.

\n\n

By the way, UUID.randomUUID() uses SecureRandom under the hood. It's cryptographically secure, but slow. If you need 10,000 strings per second — this method will disappoint you.

\n\n

2. RandomStringUtils from Apache Commons Lang

\n\n

A classic that moves from project to project. The commons-lang3 library offers a ready-made method:

\n\n
import org.apache.commons.lang3.RandomStringUtils;\n\npublic static String generateWithCommons(int length) {\n    return RandomStringUtils.randomAlphanumeric(length);\n}\n
\n\n

Elegant? Yes. Performant? Not really.

\n

Under the hood, RandomStringUtils uses java.util.Random (not cryptographically secure) and creates many temporary objects. It's sufficient for most tasks, but if you're generating millions of strings — get ready for GC pauses.

\n\n

3. Custom method with Random.nextInt()

\n\n

Let's write our own wheel. The most obvious way:

\n\n
import java.security.SecureRandom;\nimport java.util.Random;\n\npublic class RandomStringGenerator {\n    private static final String ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";\n    private static final int BASE = ALPHANUMERIC.length();\n    private final Random random;\n\n    public RandomStringGenerator() {\n        this.random = new SecureRandom(); // for cryptographic security\n    }\n\n    public String generate(int length) {\n        StringBuilder sb = new StringBuilder(length);\n        for (int i = 0; i < length; i++) {\n            sb.append(ALPHANUMERIC.charAt(random.nextInt(BASE)));\n        }\n        return sb.toString();\n    }\n}\n
\n\n

What's important here?

\n
    \n
  • We use StringBuilder with a known capacity — no unnecessary expansions.
  • \n
  • SecureRandom guarantees that the output cannot be predicted. For tokens — a must-have.
  • \n
  • The alphabet is defined as a string — 62 characters (26+26+10). You can add special characters.
  • \n
\n\n

But there's a problem: SecureRandom can be slow on Linux (waiting for entropy). If speed is more important than security — use ThreadLocalRandom.current().

\n\n

4. Optimization with char[] and ThreadLocalRandom

\n\n

Want to squeeze out maximum performance? Let's ditch StringBuilder and work directly with a character array:

\n\n
import java.util.concurrent.ThreadLocalR                

Blogs

Book Recommendations